Kirankumar Dafda
Kirankumar Dafda

Reputation: 2384

Set ajax call only when the new record inserted to database

I wants to get updated comment from chat list to the page without refreshing the page, Thats I have used ajax call for the list but I have to call this function for every 5 seconds to check whether new chat is inserted or not to the database,

$(document).ready(function(){
    setInterval(function(){
        $.ajax({
            type:'POST',
            url: baseUrl+"chat",
            cache: false,
            data: dataString,
            crossDomain: true,
            success: function(data){
                var getData = JSON.parse(data);
                if(getData.status == "success")
                {   
                    for(i=0;i<getData.chat.length)
                    {
                        $("chatList").text("");
                        $("chatList").append("<span class='black'>"+getData["chat"][i].name+" : <span class='blue'>"+getData["chat"][i].comment+"</span>");
                    }
                }
                else
                {
                    alert(getData.message);
                } 
            }
        });
    },5000);
});

So I wants to know if there is any easy way to do this or from PHP MySQL it is possible to send page a new comment inserted notification ?

Upvotes: 1

Views: 1461

Answers (3)

Spider
Spider

Reputation: 524

You can use socket.io api to get real-time information to the client..

Upvotes: 0

M.Tanzil
M.Tanzil

Reputation: 1995

Best practice is to use HTML5 WEB WORKERS.

HTML5 Web Workers

The problem with JavaScript on the browser is that it runs on a single thread. In other words, two scripts or processes cannot run simultaneously. If you are processing JavaScript after page load, the end user cannot interact dynamically with the page. The JavaScript will not handle UI events while processing something else. If you process something large before page load, the end user has to wait all-together which is a horrible user experience.

Upvotes: 2

boehm_s
boehm_s

Reputation: 5544

You can use a websocket, socket.io for example. That will allow you to send notifications from the server to the client. So, when you recieve data from your chat (cient) in your API (server), after updating the database, you will have to send a 'notification' to your client.

When your client get the notification, you can make your AJAX call :

socket.on('notification', function(){
  doYourAJAXStuff();
});

Upvotes: 1

Related Questions