I\'m looking to implement a chat room using PHP/Javascript (Jquery) with both group chat and private chat features.
The problem is how to continually update the inte
I used this book/tutorial to write my chat application:
AJAX and PHP: Building Responsive Web Applications: Chapter 5: AJAX chat and JSON.
It shows how to write a complete chat script from scratch.
You can also use Comet with PHP.
From: zeitoun:
Comet enables web servers to send data to the client without having any need for the client to request it. Therefor, this technique will produce more responsive applications than classic AJAX. In classic AJAX applications, web browser (client) cannot be notified in real time that the server data model has changed. The user must create a request (for example by clicking on a link) or a periodic AJAX request must happen in order to get new data fro the server.
I'll show you two ways to implement Comet with PHP. For example:
using server timestampThe first shows the server date in real time on the clients, the displays a mini-chat.
You need:
backend.phpindex.htmlThe backend script (backend.php) will do an infinite loop and will return the server time as long as the client is connected.
Comet php backend
';
echo 'comet.printServerTime('.time().');';
echo '';
flush(); // used to send the echoed data to the client
sleep(1); // a little break to unload the server CPU
}
?>
The frontend script (index.html) creates a "comet" javascript object that will connect the backend script to the time container tag.
Comet demo
The server time will be shown here
You need the same as in method 1 + a file for dataexchange (data.txt)
Now, backend.php will do 2 things:
The frontend script (index.html) creates the tags hat will contains the chat messages comming from "data.txt" file, and finally it create a "comet" javascript object that will call the backend script in order to watch for new chat messages.
The comet object will send AJAX requests each time a new message has been received and each time a new message is posted. The persistent connection is only used to watch for new messages. A timestamp url parameter is used to identify the last requested message, so that the server will return only when the "data.txt" timestamp is newer that the client timestamp.
Comet demo
You can also have a look at other chat applications to see how they did it:
http://hot-things.net/?q=blite - BlaB! Lite is an AJAX based and best viewed with any browser chat system that supports MySQL, SQLite & PostgreSQL databases.
Gmail/Facebook Style jQuery Chat - This jQuery chat module enables you to seamlessly integrate Gmail/Facebook style chat into your existing website.
Writing a JavaScript/PHP Chat Server - A tutorial
CometChat - CometChat runs on standard shared servers. Only PHP + mySQL required.