You want AJAX push (server sends update to client only when there's something new). See an example here: http://provatosys.com/bid.html
Something like this would elaborate the 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 reply from your server (process_request.php) until there's something to send (using something like while (($msg=new_msgs()) === false) {sleep(timeout);}
for example) or the request times out and a new poll is send from the client (setTimeout("sendRequest("+uid+")",timeoutinmillisecs);
). This is called Long polling and for applications like chats is more efficient than replying with an empty response.
You can find more info here: How do I implement basic "Long Polling"?
and here: Make AJAX call wait for event in php
and here: Comet (programming)
[EDIT] As a very much needed and more efficient alternative to long polling, now all major browsers support websockets. The RFC6455 has entered the status of (proposed) standard in 2011 (which means it has exited draft status and hasn't had any changes since). The best implementation in PHP is probably Ratchet (as far as I know the most up to date with the standard by far). Here is a tutorial on how to build a web chat using it: http://socketo.me/docs/hello-world