How to post/send form fields return by ajax to the server using jQuery $.post

Viewed 166

Good day fellows, I'm displaying a form via ajax based on some drop downs menus. User can can select the class on one dropdown and subject on another, which in turn returns a list of students in that class.

This is formated in a form like manner that allows user to enter scores of subjects that a student have acquire. This is how the form looks after user have selected their preferences: enter image description here

I want when the save button is click and after user have enter the score, it should be send to the database. I'm facing few problems:

  1. When the score field is empty(since I added a required attribute) it doesn't validate that the field is empty, but rather send a request to the file that is responsible to insert records.
  2. When the request reaches the file responsible to insert records(create_score.php) it's like no values were send through the form. I know this because I var_dump($_POST) and it return this array(0) { }

This is the script I'm using to return the file:

$(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('');
    }   
}); 

When the submit is click the is how I structure my code to post values to file responsible to insert records(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>');

This is how I'm returning the form(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";
}

Contents of file responsible to insert records (create_score.php)

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

I'm open to feed backs and suggestions on ways I can make this work. Thanks!!!

UPDATE This is how I'm now displaying my form

$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 Answers
Related