weixin_33721344 2016-03-23 11:58 采纳率: 0%
浏览 50

如何延迟Ajax请求?

I have a form that posts data to a server side page where the data is inserted into a mysql database and then a row count of the database is performed and the result returned to the form page where it is then displayed.

I am using an ajax to fetch the row count data and I'm wondering if it is possible to delay the Ajax call until the data has been inserted into the database so I can get an accurate row count that would include the data just submitted? The current code works but only shows a row count before the form has been submitted. I have to reload the page to get a true result.

Form.php

<form class="form-inline" action="" id="myform" form="" method="post">
 <!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="name"></label>  
  <div class="col-md-8">
  <input id="name" name="name" type="text" placeholder="name" class="form-control input-lg" required>
    </div>
</div>

<!-- Button -->
<div class="form-group">
  <label class="col-md-4 control-label" for="submit1"></label>
  <div class="col-md-4">
    <button id="submitButtonId" name="submit1" class="btn btn-primary btn-xl">Submit</button>
  </div>
</div>
</form>

<div id="count"></div>
</div>

The jquery

<script>
//Post data from form
$(document).ready(function(){
$("#submitButtonId").on("click",function(e){
  e.preventDefault();

var formdata = $(this.form).serialize();
    $.post('server.php', formdata,
           function(data){
  //Reset Form
$('#myform')[0].reset(); 
          });

return false;
});
});
</script>
<script>

//Fetch Rowcount from server.php
  $(document).ready(function(){
$.ajax({
                    url: 'data.php',
                    dataType: "json",
                    success: function (data) {
                    $("#count").html(data.count);

}
});
});
</script>

Server.php

<?php
//Connect to db
include_once("db_conx.php");
if( isset($_POST['name']) ){
$name= mysqli_real_escape_string($db_conx,$_POST['name']);

//Update Database 
$stmt = $db_conx->prepare('INSERT INTO myTable  set name=?');
$stmt->bind_param('s',$name);
$stmt->execute();
}
//Count Rows
$sql="SELECT name FROM myTable";
$query = mysqli_query($db_conx, $sql);
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($query);

// send output
$my_data=array(count=>"$rowcount");

echo json_encode($my_data,true);
?>
  • 写回答

3条回答 默认 最新

  • weixin_33674976 2016-03-23 12:04
    关注

    you can call the count row function after the post like this:

     $.post('server.php', formdata,
         function(data) {
             //Reset Form
             $('#myform')[0].reset();
             $.ajax({
                 url: 'data.php',
                 dataType: "json",
                 success: function(data) {
                     $("#count").html(data.count);
                 });)
         });
    
    评论

报告相同问题?