Question

I want to keep my website updated one new information is added in the database. I can't use Node.js and Comet Programming, and Javascript's setInterval seems to be a bad idea because of too many requests.

Now I am using something like this :

Javascript :

var url = "path_to/file.php";
var req = xmlhttp();
req.open("GET", url, true);
req.send(null);
poll = setInterval(getResponse, 100);
function getResponse()
{
  var data = req.responseText;
  var res = document.getElementById("response");
  res.innerHTML = data;
}

PHP :

<?php
  set_time_limit(0);
  ob_start(); 

   while(true)
   {
    #CODE
    flush(); 
    ob_flush(); 
    sleep(0.3); 
   }

  flush(); 
  ob_flush(); 
?>

Is this a good Idea? Can I use it with no problems? Maybe someone knows the better way to keep persistent connection? (on my website will be about 500 online users)

Was it helpful?

Solution

Push via WebSockets is an alternative, but only works for the latest version of browsers.

Your script has the disadvantage of asking every 100ms (this is very short), also when the latest ajax responses haven't arrived. I would change the script to ask the server for changes only if the previous ajax has arrived and a minimum time (timeout) since the last ajax has reached.

E.g. (untested):

function getResponse() {
    var data = req.responseText;
    var res = document.getElementById("response");
    res.innerHTML = data;
    setTimeout(getResponse, 500);
}
var url = "path_to/file.php";
var req = xmlhttp();
req.open("GET", url, true);
req.send(null);
getResponse();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top