Thursday, October 1, 2015

Ajax Queue Example Code


Although this is not what ajax is meant for, but sometimes application requirements force us to implement various hacks. For example, ajax is usually done for light-weight request. But in my case, I am using it for an alternative to form submission. Each of these submissions causes heavy load at server end. So I cannot allow more than one concurrent ajax call to reach the server. This simple solution worked as a charm.

Javascript code:

var ajaxQueue = $({});
var currentRequest = null;
$.ajaxQueue = function( ajaxOpts ) {
    // Hold the original complete function.
    var oldComplete = ajaxOpts.complete;
    // Queue our ajax request.
    ajaxQueue.queue(function( next ) {
        // Create a complete callback to fire the next event in the queue.
        ajaxOpts.complete = function() {
            // Fire the original complete if it was there.
            if ( oldComplete ) {
                oldComplete.apply( this, arguments );
            }
            // Run the next query in the queue.
            next();
        };
        // Run the query.
        currentRequest = $.ajax( ajaxOpts );
    });
};

// Ajax calls
function ajaxCall() {
    $.ajaxQueue({
        type: "POST",
        url: '/echo/json/',
        async: true,
        cache: false,
        success: function( result ) {
            // process response
        }
    });
}

// Abort method
function abortAjaxQueue() {
    ajaxQueue.clearQueue();
    if (currentRequest) {
        currentRequest.abort();
    }
}

Disclaimer

This is not my own code, this is community developed, thanks to this stackoverflow question and its accepted answer by sroes. Tested using JQuery versions 1.9.1 to 2.3.1

Play with this code in JSFiddle