2

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)

John
  • 7,500
  • 16
  • 62
  • 95
  • What are You attempting to do and what is the desired result? Why is there this infinite loop? This `flush(); ob_flush();` after Your `while(true){..}` will never be executed... – shadyyx Jun 08 '12 at 11:28
  • @shadyyx This example will be for a chat system, but I also have to display new information on the website once it is added to the database. (I my oppinion sending Ajax Requests Each Second will slow down a whole page). [ Thanks I will remove these lines. ] – John Jun 08 '12 at 11:32
  • I have never seen such implementation but AJAX requesting. If You consider each second is very time and server resources consuming You still can request the changes each 3 seconds or so... – shadyyx Jun 08 '12 at 11:46

1 Answers1

2

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();
scessor
  • 15,995
  • 4
  • 43
  • 54