user2507316
user2507316

Reputation: 169

how to update chat window with new messages

setInterval(function{

 //send ajax request and update chat window


}, 1000)

is there any better way to update the chat with new messages? is this the right way to update the chat using setInterval?

Upvotes: 0

Views: 1253

Answers (2)

MKroeders
MKroeders

Reputation: 7742

There are two major options (or more said popular ways)

Pulling

First is pulling, this is what you are doing. Every x (milli)seconds you check if the server config has changed.

This is the html4 way (excluding flash etc, so html/js only). For php not the best way because you make for a sinle user a lot of connections per minute (in your example code at least 60 connections per second).

It is also recommended to wait before the response and then wait. If for example you request every 1 second for an update, but your response takes 2 seconds, you are hammering your server. See tymeJV answer for more info

Pushing

Next is pushing. This is more the HTML5 way. This is implemented by websockets. What is happining is the client is "listing" to a connection and waiting to be updated. When it is updated it will triger an event.

This is not great to implement in PHP because well you need a constanct connection, and your server will be overrun in no time because PHP can't push connections to the background (like Java can, if I am correct).

I made personally a small chat app and used pusher. It works perfectly. I only used the free version so don't know how expensive it is.

Upvotes: 3

tymeJV
tymeJV

Reputation: 104775

Pretty much yes, one minor tweak, rather than encapsulate an AJAX call inside an interval (this could result in pooling of unreturned requests if something goes bad on the server), you should throw a setTimeout into the AJAX callback to create a recursive call. Consider:

function callAjax() {
    $.ajax(options).done(function() {
        //do your response
        setTimeout(callAjax, 2000);
    });
}

callAjax();

Upvotes: 0

Related Questions