【问题标题】:Add the last added database record right after form submission在表单提交后立即添加最后添加的数据库记录
【发布时间】:2015-07-11 13:58:33
【问题描述】:

我有一个注册表单,我想显示所有的注册人。我想输出数据库中的任何记录,然后一旦提交表单以注册另一个显示该记录。

我可以成功注册记录并使用 ajax 显示它们,但是它不会加载最后注册的记录,直到您重新加载/返回页面。我希望最后一条记录在表单提交后立即加入其兄弟。我感谢您提出的任何建议。

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

});

【问题讨论】:

    标签: php ajax mysqli


    【解决方案1】:

    我想出了一个解决办法。基本上,我运行脚本以在页面加载时显示数据库的记录。然后我再次使用基本相同的脚本,并在成功完成表单后再次运行它。这样,我们只在需要时扫描数据库中的新记录。不是最优雅或最有效的方式,但她的工作就像一个魅力。

    所以在我的 process_student_registration.php 中,我将它添加到了成功消息中。

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

    【讨论】:

      【解决方案2】:

      我遇到了类似的问题...您正在处理两个不同的 php 文件:

      process_student_registration.phpfetch_students.php

      我相信如果您从一个文件中完成所有处理,您的问题可能会得到解决:

      您只传递了两条数据。您可以通过inputs 收集数据,而不是从form 收集数据,然后直接访问jQuery

      您的收藏 HTML 将如下所示:注意破折号替换为下划线。

       <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>
      

      你的 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);
                  });
          });     
      });
      

      你的 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
      
      
      ?>
      

      【讨论】:

      • 感谢您的解决方案,但我最终选择了不同的路线,并且能够完成我想要的。
      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多