如何发布/发送表单字段由ajax返回到服务器使用jQuery $ .post

时间:2017-05-30 09:48:54

标签: javascript php jquery ajax forms

美好的一天,我正在根据一些下拉菜单通过 ajax 显示表单。用户可以在一个下拉列表中选择,在另一个下拉列表中选择主题,然后返回该类中的学生列表。

这是以类似的方式形成的,允许用户输入学生已经获得的分数。这是用户选择其首选项后表单的外观: enter image description here

我想在点击保存按钮时,在用户输入分数后,应将其发送到数据库。 我遇到的问题很少:

  1. 当得分字段为空(因为我添加了必需属性)时,它不会验证该字段是否为空,而是向负责插入记录的文件发送请求。
  2. 当请求到达负责插入记录的文件(create_score.php)时,就像没有通过表单发送任何值一样。我知道这是因为我var_dump($_POST)并且它返回array(0) { }
  3. 这是我用来返回文件的脚本:

    $(document).ready(function() {
    $('#subject_id').on('change', function(){
        var subject_id = $('#subject_id').val();
        var class_id = $('#class_id').val();
        var term = $('#term').val();
    
        if (subject_id != '' || class_id != '') {
          $.ajax({
            url:"includes/ajax/read_student_score_form.php",
            method:"post",
            data:{"subject":subject_id, "class":class_id, "term":term},
            dataType:"text",
            success:function(data){
              $("#result").html(data);
            }
          });
        } else {
          $("#result").html('');
    
        }   
    }); 
    
    $('#class_id').on('change', function(){
        var subject_id = $('#subject_id').val();
        var class_id = $('#class_id').val();
        var term = $('#term').val();
    
        if (subject_id != '' || class_id != '') {
          $.ajax({
            url:"includes/ajax/read_student_score_form.php",
            method:"post",
            data:{"subject":subject_id, "class":class_id, "term":term},
            dataType:"text",
            success:function(data){
              $("#result").html(data);
            }
          });
        } else {
          $("#result").html('');
        }   
    });
    
    $('#term').on('change', function() {
      /* Act on the event */
        var subject_id = $('#subject_id').val();
        var class_id = $('#class_id').val();
        var term = $('#term').val();
    
        if (subject_id != '' || class_id != '') {
            $.ajax({
              url:"includes/ajax/read_student_score_form.php",
              method:"post",
              data:{"subject":subject_id, "class":class_id, "term":term},
              dataType:"text",
              success:function(data){
                $("#result").html(data);
              }
            });
        } else {
          $("#result").html('');
        }   
    }); 
    

    当单击提交时,我是如何构建我的代码以将值发布到负责插入记录的文件(create_score.php

    $(document).on('click', '#savebtn', function(event) {
        event.preventDefault();
    
        // this is where I'm testing if the button is working
        alert("Button click");
        console.log("Button click for console");
    
        var form = $('#st_score_form');
        var formdata = form.serialize();
    
        $.post("includes/ajax/create_score.php", formdata)
        .done(function(data){
          $("#success").fadeIn('slow', function(){
            $("#success").html('<div class="alert alert-info alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true"><i class="glyphicon glyphicon-remove-circle"></i></button><b><i class="fa fa-check"></i>Alert! </b>'+data+'</div>');
          });    
        })
        .fail(function(data){
            $("#success").fadeIn('slow', function(){
                 $("#success").html('<div class="alert alert-warning alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true"><i class="glyphicon glyphicon-remove-circle"></i></button><b><i class="fa fa-warning"></i>Alert! </b>'+data+'</div>');
             });
        });
    
    });
    $('body').append('<button id="#savebtn"></button>');
    

    这就是我返回表单(read_student_score_form.php)的方式:

    if (mysqli_num_rows($result) > 0) {
        # code...
        $output .= '<h4 align="center">Periodic Report</h4>';
        $output .= '<div class="table-responsive">
    
                        <table class="table table-bordered">
                            <tr>
                                <th scope="row" colspan="1">Subject</th>
                                <td colspan="5">'.$subject["subject_name"].'</td>
    
                                <th scope="row">Class</th>
                                <td>'.$class['class_name'].'</td>
    
                                <th scope="row">Period</th>
                                <td>'.$period.'</td>
                            </tr>';
            $output .= '</table>';
            $output .= '<table class="table table-bordered table-condensed table-responsive table-striped">
                            <thead>
                                <tr>
                                    <th>Student</th>
                                    <th>Score</th>
                                    <th>Operations</th>
                                </tr>
                            </thead>';
                $output .= '<tbody>';
                    while ($row = mysqli_fetch_array($result)) {
                        # code...
                        $output .= '<form action="#" method="post" id="st_score_form">';
                            // unseen fields values that will be send
                            $output .= '<tr style="display: none;">';
                                $output .= '<td><input type="text" name="student_id" value="'.$row['student_id'].'"></td>';
                                $output .= '<td><input type="text" name="subject_id" value="'.$subject_id.'"></td>';
                                $output .= '<td><input type="text" name="class_id" value="'.$class_id.'"></td>';
                                $output .= '<td><input type="text" name="term" value="'.$term.'"></td>';
                            $output .= '</tr>';
                            // -- end of unseen fields
    
                            $output .= '<tr>';
                                $output .= '<td>'.$row["first_name"]." ".substr($row["middle_name"], 0, 1).". ".$row["surname"].'</td>';
                                $output .= '<div class="form-group">';
                                    $output .= '<td><input type="number" min="59" max="100"  name="score" class="form-control" required="required"></td>';
                                    $output .= '<td><input type="submit" name="savebtn" id="savebtn" value="Save" class="btn btn-info form-control"></td>';
                                $output .= '</div>';
    
                            $output .= '</tr>';
                        $output .= '</form>';
                    }
                $output .= '</tbody>';
            $output .= '</table>';
        $output .= '</div>';            
        echo $output;
    } else {
        echo "Data not found";
    }
    

    负责插入记录的文件内容(create_score.php

    if (isset($_POST)){
        // just testing to see values posted
        echo var_dump($_POST);
    }
    

    我愿意提供有关如何使其发挥作用的反馈和建议。感谢!!!

    更新这就是我现在显示表单的方式

    $output .= '<form action="#" method="post" id="st_score_form">';
                        while ($row = mysqli_fetch_array($result)) {
                            # code...
                                // unseen fields values that will be send
                                $output .= '<tr style="display: none;">';
                                    $output .= '<td><input type="text" id="student_id" name="student_id" value="'.$row['student_id'].'"></td>';
                                    $output .= '<td><input type="text" name="subject_id" value="'.$subject_id.'"></td>';
                                    $output .= '<td><input type="text" name="class_id" value="'.$class_id.'"></td>';
                                    $output .= '<td><input type="text" name="term" value="'.$term.'"></td>';
                                $output .= '</tr>';
                                // -- end of unseen fields
    
                                $output .= '<tr>';
                                    $output .= '<td>'.$row["first_name"]." ".substr($row["middle_name"], 0, 1).". ".$row["surname"].'</td>';
                                    $output .= '<div class="form-group">';
                                        $output .= '<td><input type="number" min="59" max="100"  name="score" class="form-control" required="required"></td>';
                                        $output .= '<td><input type="submit" name="savebtn" id="savebtn" value="Save" class="btn btn-info form-control"></td>';
                                    $output .= '</div>';
    
                                $output .= '</tr>';
                        }
                    $output .= '</form>';
    

1 个答案:

答案 0 :(得分:0)

您有多个具有相同ID的元素,具体为

id="savebtn"

第一个附加了jQuery,第二个来自电线,你也尝试添加那个......这可能是一个混乱,尝试隔离或更改按钮引用,或类,尝试切换到班级和沟渠ID一劳永逸,我很久以前就做过,我的生活变得更好了:)

另外,您的问题编号 1)尝试以与其他事件相同的方式添加检查

$(document).on('click', '#savebtn', function(event) {
    event.preventDefault();
    var form = $('#st_score_form');
    var formdata = form.serialize();
    // check for value if not empty
    var subject_id = $('#subject_id').val();
    var class_id = $('#class_id').val();
    var term = $('#term').val();

    if (subject_id != '' || class_id != '') {
      $.post("includes/ajax/create_score.php", formdata)
      .done(function(data){
        $("#success").fadeIn('slow', function(){
          $("#success").html('<div class="alert alert-info alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true"><i class="glyphicon glyphicon-remove-circle"></i></button><b><i class="fa fa-check"></i>Alert! </b>'+data+'</div>');
        });    
      })
      .fail(function(data){
          $("#success").fadeIn('slow', function(){
               $("#success").html('<div class="alert alert-warning alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true"><i class="glyphicon glyphicon-remove-circle"></i></button><b><i class="fa fa-warning"></i>Alert! </b>'+data+'</div>');
           });
      });
    }
});

您的问题编号

2)当您从read_student_score_form.php页面获得结果时,尝试在浏览器控制台中运行此操作以查看您是否有任何结果,,那是在您尝试将其发送到服务器之前,

var form = $('#st_score_form');
var formdata = form.serialize();

运行它,并在这里得到你的结果,所以也许我们可以继续这个问题,

更新:

你错误地循环...看看你在php中的时间,那会渲染多个<form action="#" method="post" id="st_score_form">而这是错误的..之前移动它,而这样的事情:

<?php
    $output .= '<form action="#" method="post" id="st_score_form">';
    while ($row = mysqli_fetch_array($result)) {

    } // end while
    $output .= '</form>';