Alvaro
Alvaro

Reputation: 41605

Check for changes with jquery and a database

I am doing a notification system. When a new post is published, users will be notified immediately by an small notification on the screen.

I am currently using this:

setInterval(function(){
 checkForChanges();
}, 2*1000); 



function checkForChanges(){
    $.post("http://"+ document.domain + "/posts/checkForChanges/",
        function(dat){
           if(dat>0){
              ....
              /*create notification*/
           }

    });
}

And i was wondering if this is the correct way to do it or not. Because, this is calling a PHP function every 2 seconds and making a query to the database. In case there are no new changes, it won't do anything...

Thanks.

Upvotes: 0

Views: 401

Answers (2)

Sandip Karanjekar
Sandip Karanjekar

Reputation: 850

This is also fine.You can do it with websocket also-
http://socketo.me/

Upvotes: 1

GolezTrol
GolezTrol

Reputation: 116170

Yes, polling is the right way. There's no way to send notifications from a server to a client. The client has to ask for them.

2 seconds might be too often. If you could get away with 10 or more, it might be better, but all depends on the number of users, the complexity (weight) of the checks to perform and the need to be 'near realtime'.

Upvotes: 2

Related Questions