Example of real time refresh display data implemented by php+jQuery ajax

  • 2021-12-21 04:16:17
  • OfStack

This paper describes the real-time refresh display data function realized by php + jQuery ajax. Share it for your reference, as follows:

Create a data table: demo


--
--  Structure of the table  `demo`
--
CREATE TABLE IF NOT EXISTS `demo` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(20) COLLATE utf8_bin NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=5 ;
--
--  Drop the data in the table  `demo`
--
INSERT INTO `demo` (`id`, `name`) VALUES
(1, ' Lei Jun '),
(2, ' Pony Ma '),
(3, ' Li Yanhong '),
(4, ' Jack Ma ');

Server file: demo. php


<?php
$mysqli = new mysqli("localhost","root","","test");
$mysqli->set_charset('utf8');
$query = 'SELECT * FROM demo';
$result = $mysqli->query($query);
$arr = $result->fetch_all(MYSQLI_ASSOC);
$info = json_encode($arr);
echo $json = '{"success":true,"info":'.$info.'}';

Display data page: fresh. html


<html>
<head>
  <meta charset='utf-8'>
  <title>hello</title>
</head>
<body>
<script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
<script>
  function check(){
    $.ajax({
      type:"GET",
      url:"./demo.php",
      dataType:"json",
      success:function(data){
        if(data.success){
          var count = data.info.length;
            for(i=0;i<count;i++){
              var dom = "<tr align='center' id='"+data.info[i].id+"'><td>"+data.info[i].id+"</td><td>"+data.info[i].name+"</td></tr>";
              var tag = '#'+data.info[i].id;
              if(!$(tag).length){
                $("#info").append(dom);
              }
            }
        }else{
          alert('error');
        }
      },
      error:function(res){
        alert(res.status);
      }
    });
  }
  window.setInterval(check, 1000); // Execute per second 1 Times 
</script>
<body>
  <div style='width:600px;margin:0 auto;'>
    <table border='1' width="600px">
      <thead>
        <tr><th>id</th><th>name</th></tr>
      </thead>
      <tbody id='info'>
        <tr align='center' id='111'><td>111</td><td> Test </td></tr>
      </tbody>
    </table>
  </div>
</body>
</html>

For more information about PHP, please see the topics of this site: "Summary of PHP+ajax Skills and Applications", "Summary of PHP Network Programming Skills", "Summary of php String (string) Usage", "Introduction Tutorial of php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: