简体   繁体   中英

Long Polling in AJAX using php

I am using AJAX for refreshing some part of the page using AJAX, so that i don't have to reload the page again & again.
But i want the table to refresh only when there is a change ( long polling ). But i am not getting how to do that. I have tried using for loops with break statement but i am not getting the proper logic i guess.
The files are as follows
getuser.php

<!DOCTYPE html>
<html>
<head>
<style>
table {
    width: 100%;
    border-collapse: collapse;
}

table, td, th {
    border: 1px solid black;
    padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
$conn = mysqli_connect('localhost','root','','bondplus');
if (!$conn) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($conn,"bondplus");
$sql="SELECT * FROM `user_details`";
$result = mysqli_query($conn,$sql);
echo "<table>
<tr>
<th>Firstname</th>
<th>Mobile</th>
<th>Email</th>
<th>Type</th>
<th>Hometown</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['u_name'] . "</td>";
    echo "<td>" . $row['mob'] . "</td>";
    echo "<td>" . $row['email'] . "</td>";
    echo "<td>" . $row['type'] . "</td>";
    echo "<td>" . $row['address'] . "</td>";
    echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
</body>
</html>

trefresh.php

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
   <title>AJAX Example</title>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   <script type="text/javascript" src="reloader.js"></script>
</head>

<body onload="reloadData()">
<p> HELLO There!</p>
   <div id="currentData" align="center">
      <p>Loading Data...</p>
   </div>
</body>

<script>
var req;

function reloadData()
{
   var now = new Date();
   url = 'getuser.php?' + now.getTime();

   try {
      req = new XMLHttpRequest();
   } catch (e) {
      try {
         req = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
            req = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (oc) {
            alert("No AJAX Support");
            return;
         }
      }
   }

   req.onreadystatechange = processReqChange;
   req.open("GET", url, true);
   req.send(null);
}

function processReqChange()
{
   // If req shows "complete"
   if (req.readyState == 4)
   {
      dataDiv = document.getElementById('currentData');

      // If "OK"
      if (req.status == 200)
      {
         // Set current data text
         dataDiv.innerHTML = req.responseText;

         // Start new timer (1 min)
         timeoutID = setTimeout('reloadData()', 6000);
      }
      else
      {
         // Flag error
         dataDiv.innerHTML = '<p>There was a problem retrieving data: ' + req.statusText + '</p>';
      }
   }
}
</script>
</html>

Check for the if(req.status == 304) in your code which represents no modification in the response. If not 304 then you can update the table.

First, I would like to give you 2 important advices :

  • Use a JavaScript framework to perform Ajax operations like JQuery or AngularJS
  • Always seperate your layers and never mix code, it will be very polluted and not maintainable
  • Answer :

    back-end : Create an EventLayer in your project

    It will receive a signal from another entity that something new was happened, for example: you can use ActiveMQ OR it will send a request each N seconds to an external entity to check if there is something new ( you can store flag in memcache or in synchronized Data Source Server like ANYEM ), and after that flush data (data creation will be, of course created by a business layer)

    front-end pretty simple, you will loop on your own Ajax, example

    function ajaxLongPollingManager() {
        $.ajax({
          url: "yourproject.event.php"
        }).done(function(response) {
          // do your job ....
          // ...
          // and loop back
          ajaxLongPollingManager();
        }).fail(function(response) {
          // manage/handle your errors
          // ...
          // and loop back
          ajaxLongPollingManager();
        });
    }
    

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM