在表单提交后立即添加最后添加的数据库记录

I have a registration form and I want to display all of the registrants. I want to output whatever records are in the database and then once the form is submitted to register another display that record as well.

I can successfully register the records and display them using ajax however It does not load the last registered record until you reload/comeback to the page. I want the last record to just join its brethren right after the form submits. I appreciate anything you can suggest.

home.php

<form id="register-student" method="post" action="process_student_registration.php" class="basic-form not-toggled">
    <h2>Enter Student Info to Register</h2>
    <fieldset id="student-name-group" class="form-group">
      <div class="split">
        <fieldset id="student-firstname-group">
          <label for="student-first-name">First Name:</label>
          <input id="student-first-name" type="text" name="student_first_name">
        </fieldset>
      </div>
      <div class="split">
        <fieldset id="student-lastname-group">
          <label for="student-last-name">Last Name:</label>
          <input id="student-last-name" type="text" name="student_last_name">
        </fieldset>
      </div>
    </fieldset>
    <fieldset class="submit-button">
      <div id="loading" class="hidethis"><img id="loading-image" src="../../images/ajax-loader.gif" alt="Loading..." /></div>
      <button id="register-student-button" type="submit" class="btn btn-success" name="register-student-button">Register Student</button>
    </fieldset>
  </form>
  <script>
     $(document).ready(function() { 
         var students = $.ajax({    //create an ajax request to load_page.php
            type: "GET",
            url: "fetch_students.php",             
            dataType: "html",   //expect html to be returned                
            success: function(response){                    
                $("#registered-students").html(response); 
                //alert(response);
            }

        });
    });
  </script>
<div id="registered-students"></div><!--End # registered-students-->

fetch_students.php

<?php
//Fetch the Students

//First lets make sure the user is allowed
require_once('../auth/agency_session.php');
//App Functions
require_once('../../includes/functions/app_functions.php');
//Agents Home Page
require_once('../../db_config.php');
$db_connect = connectDB($mysqli);
$agency_id = $_SESSION['ID'];

//Here we display all the students the agent has registered
//First check the connection
if(!mysqli_connect_errno()){
    if($stmt = $db_connect->prepare("SELECT student_id, student_first_name, student_last_name, student_email FROM students WHERE agency_id = ?")){
        //Bind Parameters
        $stmt->bind_param('i', $agency_id);
        //Execute
        $stmt->execute();
        //Store Results
        $stmt->store_result();
        //Get the rows
        $num_rows = $stmt->num_rows;
        //Bind the results
        $stmt->bind_result($student_id, $student_first_name, $student_last_name, $student_email);
        if($stmt->num_rows < 1){
            echo'<h3>No Students Registered</h3>';
        }
        else{ 
            //Fetch the values
            echo'<h3>Registered Students</h3>';
            echo'<ul class="grid">';
            while($stmt->fetch()){
                echo '<li id="'.$student_id.'" class="col"><a href="student_application/student_index.php?student='.$student_id.'">'.$student_first_name.' '.$student_last_name.'<span>'.$student_email.'</span></a></li>';
            }//End While
            echo'</ul>';
        }//End else
    }//End if no prepare statment happens
}//End if No connection
?>

process_student_registration.php

jQuery(document).ready(function($){
// Get the form and place it into a variable
var form = $('#register-student');
//Creating an Event Listener for the submit buttom on the contact form
$(form).submit(function(event){
    $('.form-group').removeClass('.has-error');//Remove the error class on the things that have the error class
    $('.error-message').remove();//Remove the error messages completeley
    //Serialize the Form Data (Converts the data the user has entered into a key/value string that can be sent with an AJAX request)
    var formData = $(form).serialize();
    //Submit the form using AJAX
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData,
        dataType :'json',
        encode:true
        //.done refers to a successful completion of the form
    })
    .done(function(data){
        //Log the data into the console so that we can be sure what is happening
        console.log(data);
        //If we do have errors create the 
        if(!data.successmessage){
            if(data.errors){
                $('.error').remove();
                $('.error-message').remove();

                $('#register-student').addClass('form-has-error'); // add the form-has-error-class
                $('#register-student-button').after('<p class="error">Please check the errors above.</p>');

                $(form).removeClass('success');
                $('.submit-success').remove();

            if(data.errors.student_first_name){
                $('#student-firstname-group').addClass('has-error'); // add the error class to show red input
                $('#student-firstname-group').append('<div class="error-message"><p>' + data.errors.student_first_name + '</p></div>'); // add the actual error message under our input
            }
            if(data.errors.student_last_name){
                $('#student-lastname-group').addClass('has-error'); // add the error class to show red input
                $('#student-lastname-group').append('<div class="error-message"><p>' + data.errors.student_last_name + '</p></div>'); // add the actual error message under our input
            }
        }
        } else if(data.successmessage){

            //Remove the errors stuff
            $('.error').remove();
            $('.error-message').remove();
            $('#register-student').removeClass('form-has-error'); // add the form-has-error-class
            $('#blocking').removeClass('hidethis').addClass('showthis');
            $('#loading').removeClass('hidethis').addClass('showthis');
            $('.submit-success').remove();
            //Add the success stuff
            $(form).addClass('success');

            setTimeout(function(){
                $('#blocking').removeClass('showthis').addClass('hidethis');
                $('#loading').removeClass('showthis').addClass('hidethis');
                $('#register-student').append('<div class="submit-success"><p>' + data.successmessage + '</p></div>');
                $(form).find('input, :text').val('');
                //Run the Get operation on the database to add newly added records to the list

            }, 5000);
            //Clear the form upon successful completion

        }
        //.fail referes to an unsuccessful completion of the form
    })
    .fail(function(data){
        //If there is a failed submission lets log the errors
        console.log(data);
    });
    //Stop the broweser from submitting the form
    event.preventDefault();
});

});

I have figured out a solution. Basically I run the script to display records fomr the database on once on page load. Then I took basically the same script again and run it once more upon successful completion of the form. This way we only scan the database for new records as we need to. Not sre if it the most elegant or efficient way but she work like a charm.

So in my process_student_registration.php I added this to the success message.

//Run the Get operation on the database to add newly added records to the list
$.ajax({    //create an ajax request to load_page.php
    type: "GET",
    url: "fetch_students.php",             
    dataType: "html",   //expect html to be returned                
    success: function(response){                    
     $("#registered-students").html(response); 
        //alert(response);
}

I had a similar issue... you are processing from two different php file:

process_student_registration.php and fetch_students.php

I believe your problem might be solved if you do all the processing from one file:

You are only passing two pieces of data. Rather than collecting the data from a form you can collect the data through inputs and go straight to the jQuery.

Your Collection HTML would look like this: NOTICE the dashes replaced with underscores.

 <h2>Enter Student Info to Register</h2>    

    <input type="hidden" id="processStudent" value="process_student_registration.php">

    <fieldset id="student-name-group" class="form-group">
      <div class="split">
        <fieldset id="student_firstname_group">
          <label for="student_first_name">First Name:</label>
          <input id="student_first_name" type="text" name="student_first_name">
        </fieldset>
      </div>
      <div class="split">
        <fieldset id="student_lastname_group">
          <label for="student_last_name">Last Name:</label>
          <input id="student_last_name" type="text" name="student_last_name">
        </fieldset>
      </div>
    </fieldset>
    <fieldset class="submit_button">
      <div id="loading" class="hidethis"><img id="loading_image" src="../../images/ajax_loader.gif" alt="Loading..." /></div>
      <button id="register_student_button" type="submit" class="btn btn_success" name="register_student_button">Register Student</button>
    </fieldset>

    <div id="registered-students"></div>

Your jQuery...

<script>
 $(document).ready(function() {
     $( "#register-student-button" ).click(function(){ 
        var url = $('#processStudent').val(); 
        var student_first_name = $('#student_first_name').val();    
        var student_last_name = $('#student_last_name').val();                              
        var postit = $.post( url, {student_first_name:student_first_name,student_last_name:student_last_name});     
            postit.done(function( data ) {
                alert('Student has been processed');
                $('#registered-students').html(data);
            });
    });     
});

Your PHP...

<?php
    $student_first_name = $_POST['student_first_name'];
    $student_last_name = $_POST['student_last_name'];

    // PROCESS REGISTRATION HERE AS YOU ARE



    // FETCH STUDENTS HERE AS YOU ARE


?>