douqi4673
2017-07-27 18:14
浏览 107
已采纳

无法弄清楚为什么javascript在我的php文件中不起作用

Found the code for this GPA calc on github and haven't been able to get it working. The look appears correctly, but it will not calculate the GPA and the add/delete row buttons do not work. Here is the link to the files on github. https://github.com/xandroxygen/GPACalc

<?php

    $GRADELIST = array(
        "A+"=>"4.0",
        "A"=>"4.0",
        "A-"=>"3.7",
        "B+"=>"3.4",
        "B"=>"3.0",
        "B-"=>"2.7",
        "C+"=>"2.4",
        "C"=>"2.0",
        "C-+"=>"1.7",
        "D+"=>"1.4",
        "D"=>"1.0",
        "D-"=>"0.7",
        "E"=>"0.0",
    );

    // check input
    function validate_input($data)
    {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }

    // convert grades to points per hour
    // returns -1 if grade not recognized
    function grade_convert($g)
    {   
        global $GRADELIST;
        $p = -1.0;
        if (array_key_exists($g,$GRADELIST))
        {
            $p = $GRADELIST[$g];
        }
        return $p;
    }

    // import JSON string
    $json_data=array();
    $raw_data = file_get_contents('php://input');
    parse_str($raw_data,$json_data);

    // parse form input
    $name = "";
    $points =  $hours = $gpa = 0.0;

    $name = validate_input($json_data["name"]);
    $points = validate_input($json_data["points"]);
    $hours = validate_input($json_data["hours"]);
    $classes = $json_data[0]["classes"];

    // add classes in
    foreach($classes as $c)
    {
        $c_pts_per_hour = grade_convert($c[grade]);
        if ($c_pts_per_hour > -1) // else, invalid grade (lowercase, P, IE, W, etc)
        {   
            // find grade points, multiply by class hours, add to total hours 
            $c_pts = $c_pts_per_hour * $c[hours]; 
            $points += $c_pts;
            $hours += $c[hours];
        }
    }

    // calculate and output GPA
        if (is_numeric($hours) && ($hours > 0))
        {
            $gpa = $points / $hours;
        }
    echo $name . ", your GPA is " . number_format($gpa,2) . ", and you have earned " . $hours . " total hours.";
?>

Split

<!DOCTYPE html>
<html>
<body>
<style>
    .error {color: #FF0000;}
    .input-group-btn {padding-bottom: 10px;}
    h5 {width: 50%;}
</style>
<head>
    <title>GPA Calculator</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <!-- Functions for processing and calculating gpa -->
    <script type="text/javascript" src="../Sandbox_4_App/script.js"></script>
</head>

<div class="container">
    <div class="jumbotron">
        <h1>GPA Calculator</h1>
        <p>Use your current points and hours, class enrollment, and projected grades to calculate your GPA!</p>
        <h5>I built this the first week of my current job to teach myself basic principles of web design, like client-side scripting, PHP form handling, and AJAX calls.</h5>
    </div>
</div>

<!-- Current GPA container -->
<div class="container">
    <div class="panel panel-default">
        <div class="panel-heading">Calculate GPA</div>
        <div class="panel-body">

            <!-- Form for Name/Points/Hours -->
            <form role="form" action="">
                <div class="row">
                    <div class="col-xs-4">
                        <div class="form-group">
                            <label for="name">Name: <span id="nameREQ"><small>(required)</small></span><span id="nameERR" class="error">This field is required!</span></label> 
                            <input type="text" class="form-control" id="name" name="name">
                        </div>
                    </div>
                    <div class="col-xs-4">
                        <div class="form-group">
                            <label for="curr_points">Current Points: 
                                <a data-toggle="tooltip" title="Points and hours are found on your transcript"><span class="glyphicon glyphicon-info-sign"></span></a>
                            </label>
                            <input type="text" class="form-control" id="curr_points" name="curr_points">
                        </div>
                    </div>
                    <div class="col-xs-4">
                        <div class="form-group">
                            <label for="curr_hours">Current Hours: 
                                <a data-toggle="tooltip" title="Points and hours are found on your transcript"><span class="glyphicon glyphicon-info-sign"></span></a>
                            </label>
                            <input type="text" class="form-control" id="curr_hours" name="curr_hours"><br>
                        </div>
                    </div>
                </div>
            <!-- Table for Class/Grade/Hours -->
                <table class="table table-bordered table-hover" id="tab_logic">
                <thead>
                    <tr >
                        <th class="text-center">
                            #
                        </th>
                        <th class="text-center">
                            Class
                        </th>
                        <th class="text-center">
                            Grade
                        </th>
                        <th class="text-center">
                            Hours
                        </th>
                    </tr>
                </thead>
                <tbody id="classes_list">
                    <tr id='addr0'>
                        <td>
                        1
                        </td>
                        <td>
                        <input type="text" name='class0'  placeholder='Class' class="class form-control"/>
                        </td>
                        <td>
                        <input type="text" name='grade0' placeholder='Grade' class="grade form-control"/>
                        </td>
                        <td>
                        <input type="text" name='hours0' placeholder='Hours' class="hours form-control"/>
                        </td>

                    </tr>
                </tbody>
                </table>

            <!-- Add/Delete/Submit Buttons -->
                <div class="input-group-btn">
                   <a id="add_row" class="btn btn-default pull-left">Add Row</a><a id='delete_row' class="pull-right btn btn-default">Delete Row</a>
                </div>
                <input type="submit" class="btn btn-primary" id="submit" name="submit_form">
            </form>
        </div>
    </div>       
    <div id="showGPA" class="alert alert-success">
        <a  class="close" aria-label="close">&times;</a>
        <p><span id="result"></span></p>
    </div>
</div>


</body>
</html>

Split

// --- main jQuery function ---
$(function() {
    $(".alert.alert-success").hide();
    $(".error").hide();

    // --- submit a form ---

    $(".btn.btn-primary").click(function(e) {
        e.preventDefault();
        $(".error").hide();
        $("#nameREQ").show();

        // validate name, gather input
        var name = $("input#name").val();
        if (name == "")
        {
            $("#nameREQ").hide();
            $(".error").show();
            return false;
        }
        var points = $("input#curr_points").val();
        var hours = $("input#curr_hours").val();

        // process form
        var formData = "name=" + name + "&points=" + points + "&hours=" + hours;
        $.post("getGPA.php", formData, function(data) {
                $("#showGPA").show();
                $("#result").text(data);
            });
    });

    // --- close the alert box and ready for new submit ---

    $(".close").click(function() {
        $(".alert.alert-success").hide();
    });

    // --- enable tooltips
    $(document).ready(function(){
        $('[data-toggle="tooltip"]').tooltip(); 
    });
});

Here is my updated code after making some changes. The calculating gpa part still isn't working, and the add/delete rows isn't working because I believe that section of code is missing. I am not sure how to get that add/delete row code working.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongpo5264 2017-07-27 18:34
    已采纳

    In your javascript, I don't see anything that's binding an action to your add/delete row buttons. That's probably why they don't do anything.

    Your code for submitting the form data to the PHP script is fine, although it would be better to just send an object instead of building the request body yourself, because you're currently not escaping any of the values. So if the name contains an & or / or any of a number of other characters, the request body will be invalid:

    var formData = {
        "name": name,
        "points": points,
        "hours": hours
    };
    
    // just send an object, let jQuery deal with escaping it
    $.post("getGPA.php", formData, function(data) {
        $("#showGPA").show();
        $("#result").text(data);
    });
    

    On the PHP side of things, you're accessing the raw input. That's completely unnecessary. You're performing a regular POST request and sending proper values, so you can simply get the values from $_POST. You are most definitely NOT sending JSON to the server, so calling json_decode() doesn't make sense.

    // import JSON string
    // $raw_data = file_get_contents('php://input');
    // $json_data = json_decode($raw_data, true);
    // remove those lines, they don't do anything useful.
    
    // parse form input
    $name = "";
    $points =  $hours = $gpa = 0.0;
    
    $name = validate_input($_POST["name"]);
    // note: you're sending "name" to the server, not "person_name"
    
    $points = validate_input($_POST["points"]);
    $hours = validate_input($_POST["hours"]);
    $classes = $_POST["classes"];
    

    I don't know where "classes" is coming from, because you're not sending any classes to the server.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douyue7536 2017-08-03 10:45

    i think u must parse ur post data as,try this

    // import JSON string
        $json_data=array();
        $raw_data = file_get_contents('php://input');
        parse_str($raw_data,$json_data);
    
        // parse form input
        $name = "";
        $points =  $hours = $gpa = 0.0;
    
        $name = validate_input($json_data["name"]);
        $points = validate_input($json_data["points"]);
        $hours = validate_input($json_data["hours"]);
        $classes = $json_data[0]["classes"];
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题