weixin_33725722 2016-03-22 23:17 采纳率: 0%
浏览 30

使用Ajax即时刷新

I am trying to understand ajax and want to figure out how I can refresh a div that displays a rowcount from a mysql database live as the data is entered into that database.

I have a simple form on the same page and as the data is submitted from the form to the database how can I make the div update 'live' as well?

The code I've posted here posts a name from a form which is inserted into a mysql database. Then the number of rows in the database is counted and returned as a json object. It all works fine but only refreshes the rowcount when I reload the page and I want it to refresh instantly.

Many thanks.

The form

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

<!---------Display rowcount from database--------->

The jquery

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

var formdata = $(this.form).serialize();
    $.post('data.php', formdata,
           function(data){

 //Reset Form
$('#myform')[0].reset(); 
          });

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

$(document).ready(function() { 

$.ajax({
                    url: 'data.php',
                    dataType: "json",
                    success: function (data) {
                    $("#count").append(data.count);
}
});    
                return false;  
});

</script>

data.php

<?php
//include db configuration file
include_once("db_conx.php");

$name= mysqli_real_escape_string($db_conx,$_POST['name']);
//Update Database
$stmt = $db_conx->prepare('INSERT INTO my_table set name?');
$stmt->bind_param('s',$name);
$stmt->execute();

//Count Rows
$sql="SELECT name FROM utility";
$query = mysqli_query($db_conx, $sql);
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($query);

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

echo json_encode($my_data,true);

?>
  • 写回答

2条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 GEO下载数据的处理报错 :函数‘Meta’标签‘"data.frame"’找不到继承方法,如何解决?
      • ¥15 DLNM模型是否可以用二分类变量作为y变量
      • ¥15 android object box 一个实体多个表怎么写
      • ¥15 temux 启用docker 服务失败
      • ¥15 Flask 使用celery发送邮件出现‘目标计算机积极拒绝‘
      • ¥60 老人用的sd卡在手机里面不知道操作了什么,导致图片和视频变成了文件,取下sd卡连接电脑就是图中的样子,后缀改为.jpg才可以,需要用系统的画图软件才能打开,文件属性还是文件,有没有批量操作的解决办法
      • ¥15 超时跳出方法代码的返回值问题
      • ¥15 汇编语言程序设计设计,ascii码求数,再求数的BCD码
      • ¥30 Mask rcnn训练自己的数据集出现问题!
      • ¥20 研究人工智能时的几个问题