doubiaokai4998 2015-05-01 17:32
浏览 96
已采纳

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

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

});

  • 写回答

2条回答 默认 最新

  • dongtang6681 2015-05-04 15:27
    关注

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?