Singleton Ajax: How to cancel previous ajax calls, instead using the last request

11/13/2013

Sometimes when you are making multiple ajax calls to the same URL to update content on a page, you want to make sure only the last ajax request makes the final call while previous calls are cancelled. That is to make sure content on your page is updated with correct data when multiple ajax calls can arrive back from backend URL at different times without any guaranteed order due to the asynchronous nature.

 

Some people come up with a solution to this problem using a counter and checking the counter value on arrival back from backend URL. I think that approach is unnecessary. Instead we can solve this problem elegantly utilizing closure in Javascript.

 

As we have similar problems to solve while working on our SyncRelease project, I ended up writing a little jQuery plugin, which I call as Singleton Ajax.

 

(function($){
    var singletonPost = null;
    var singletonGet = null;
    
    $.extend({
       'singletonPost': function(url, params, callback, dataType){
            if(singletonPost != null){
                singletonPost.abort();
            }

            singletonPost =  $.ajax({
                type: "POST",
                url: url,
                data: params,
                success: function(data){
                    singletonPost = null;
                    callback(data);
                },
                dataType : dataType || 'json'
            });
       },
       'singletonGet' : function(url, params, callback, type){
            if(singletonGet != null){
                singletonGet.abort();
            }

            singletonGet =  $.ajax({
                type: "GET",
                url: url,
                data: params,
                success: function(data){
                    singletonPost = null;
                    callback(data);
                },
                dataType : dataType || 'json'
            });
       }});

})(jQuery);

 

How to Use It?

When you want to make sure always the last ajax request to be used while canceling any prior requests, please use the singleton ajax calls similar to how you would normally do with $.get and $.post functions.

 

//using POST method
$.singletonPost(“/my-rest-url”, { “id”: 123, “query” : “hello world” }, function(data){

	//do something with data received.
           
}, ‘json’);

//using GET method
$.singletonGet(“/my-rest-url”, { “id”: 123, “query” : “hello world” }, function(data){

	//do something with data received.
           
}, ‘json’);