I am creating a chat program. This chat program has two sides(client and user). All the data is going into a database(mysql). Currently, the chat works fine. Each side types and i have a listener function that uses ajax to load the database file into the window each second or two.
The problem is, this is eating up too much bandwidth!
I was thinking about terminating the chat after a set duration or I was thinking there is a way to only update when an event happens.
Ideally this would work best in my opinion:
If the user enters new data, then it will be detected on the client side and then it will activate the function to update the chat window only at that time.
Does anything exist like this to listen in ajax/jquery/javascript?
Here is the code I am currently using to listen:
/* set interval of listener */
setInterval(function() {
listen()
}, 2500);
/* actual listener */
function listen(){
/* send listen via post ajax */
$.post("listenuser.php", {
chatsession: $('#chatsession').val(),
/* Do some other things after response and then update the chat window with response content from database window */
}, function(response){
$('#loadingchat').hide();
$('#chatcontent').show();
$('#messagewindow').show();
setTimeout("finishAjax('messagewindow', '"+escape(response)+"')", 450);
});
return false;
}
There are many ways to do it, but looking at your design I will suggest to use a technique called Comet, basically is a way to get web servers to “send” data to the client without having any need for the client to request it. It is kind of a hack if you read the code, as per my opinion.
but here goes a example that i found of how to implement this, using a simple text file:
SERVER
CLIENT:
I hope it helps.
heres a URL with more examples and some documentation (I got the example from here):
http://www.zeitoun.net/articles/comet_and_php/start