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


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>

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


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

The jquery


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

 //Reset Form

return false;

$(document).ready(function() { 

                    url: 'data.php',
                    dataType: "json",
                    success: function (data) {
                return false;  



//include db configuration file

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

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

// sending JSON output

echo json_encode($my_data,true);

  • 写回答

2条回答 默认 最新

  • weixin_33709609 2016-03-22 23:21

    If you want the server to push events to the client, you can use Websockets. There are services like Pusher that can help, it has a free plan (100 connections, 200K messages per day) and a good documentation to integrate with PHP and some popular frameworks.

    If you don't want to use websockets, you can use a more traditionnal polling : every X seconds, you make a GET request to the server asking for the count, if it changes you update it, if not you do nothing and wait for the next call. This can be setup easily with setTimeout() in Javascript.




  • ¥15 u盘问题:盘符不显示 无媒体
  • ¥50 R语言读取nc按月均值转为tif
  • ¥30 智能车串级pid调参
  • ¥15 visual studio code翻译老是错误
  • ¥20 卫星测高数据的高程转换
  • ¥15 爬取招聘网站数据信息
  • ¥15 安装完tensorflow,import tensorflow as tf后报错,如何解决?
  • ¥15 ultralytics库导出onnx模型,模型失去预测能力
  • ¥15 linux下点对点协议连接2个USB串口的硬件流量控制问题
  • ¥15 SQL数据自动生成问题