Seeking Knowledge
Seeking Knowledge

Reputation: 162

How can I implement notification system with jQuery?

I have a notification zone that I want to be updated when someone sends a message for example using jQuery or Ajax (my database is in a soap server) I want to do the soap call every second or so, how can I do that?

Upvotes: 0

Views: 350

Answers (3)

Siamak Motlagh
Siamak Motlagh

Reputation: 5136

The best way for real-time web is node.js.

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

But you can do it by setInterval or setTimeout, put an Ajax call in your interval.

var intval = setInterval( function() 
{
   $.get('url.php',  {data1: "value1", data2: "value2"},  
   function(response)
   {  
            // response  
   });  
}, 1000);

Upvotes: 1

kapa
kapa

Reputation: 78671

Instead of setInterval(), I would strongly suggest to use setTimeout().

MDN explanation:

If there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using window.setTimeout. For example, if using setInterval to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its alloted time. As such, you may find yourself with queued up XHR requests that won't necessarily return in order.

For such cases, a recursive setTimeout pattern is preferred:

(function loop(){    
    setTimeout(function(){

        // logic here

        // recurse
        loop();
    }, 1000); 
})(); 

In the above snippet, a named function loop is declared and is immediately executed. loop is recursively called inside setTimeout after the logic has completed executing. While this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed before recursing.

Upvotes: 3

Lix
Lix

Reputation: 47966

You could use a simple setInterval structure to execute AJAX calls at predefined intervals. Something like this:

setInterval(function(){
  $.get('ajax_responder.php',dataObj,function(){
    // ajax callback
    // here is where you would update the user with any new notifications.
  });
},5000);

The previous code will execute an AJAX request every 5000 miliseconds (every 5 seconds).

References:

Upvotes: 3

Related Questions