You want AJAX push (the server sends an update to the client only when there is something new). See an example here: http://provatosys.com/bid.html
Something like this will develop a request from the client:
function sendRequest(uid){ var xmlhttp; var myUserId=""; myUserId=uid; if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ displayInChat(xmlhttp.responseText)//do stuff (process response, display message) } } xmlhttp.open("GET","process_request.php?userid="+uid,true); xmlhttp.send(); setTimeout("sendRequest("+uid+")",1000); //poll every second }
Now you want to delay the response from your server (process_request.php) until something appears that can be sent (for example, using while (($msg=new_msgs()) === false) {sleep(timeout);} ) or the time of the request, and a new request is sent from the client ( setTimeout("sendRequest("+uid+")",timeoutinmillisecs); ). This is called a long poll, and for applications like chats is more efficient than answering with a blank answer.
You can find more information here: How to implement the basic "Long Polling"?
and here: Make an AJAX call to wait for an event in php
and here: Comet (programming)
[EDIT] As a very necessary and more effective alternative to lengthy polling, now all major browsers support websockets . RFC6455 introduced the status of the (proposed) standard in 2011 (which means that it left the draft status and did not have any changes since). The best implementation in PHP is probably Ratchet (as far as I know the most relevant with the standard to date). Here is a tutorial on creating a web chat using it: http://socketo.me/docs/hello-world
source share