Stop all active ajax requests
May 31, 2012     07:18:03

Several months ago I encountered a problem - "How to abort() all current requests on the project page?". If you have a project built on AJAX you'll definitely need this functionality. Moreover, if your project is not built entirely on AJAX, but uses it in some cases to accelerate the navigation on the project you would not have prevented the use of abort() for such requests.

In a single use of AJAX it is simple. The XMLHttpRequest has a abort method, which cancels the request.

// creating our request
xhr = $.ajax({
	url: 'ajax/progress.ftl',
	success: function(data) {
		//do something
	}
});

// aborting the request
xhr.abort();

The xhr object also contains a readystate which contains the state of the request(UNSENT - 0, OPENED - 1, HEADERS_RECEIVED - 2, LOADING - 3 and DONE - 4). So we can use this to check whether the previous request was completed.

// abort function with check readystate 
function abortAjax(xhr) {
	if(xhr && xhr.readyState != 4){
		xhr.abort();
	}
}

// this function usage
abortAjax(xhr);

But what if we have a lot of requests and we wand to abort all of them? Using single variable for each of them is not an option. The method I use was founded on http://stackoverflow.com/ (yep, it's not mine idea :) ).

$.xhrPool = []; // array of uncompleted requests
$.xhrPool.abortAll = function() { // our abort function
    $(this).each(function(idx, jqXHR) { 
        jqXHR.abort();
    });
    $.xhrPool.length = 0
};

$.ajaxSetup({
    beforeSend: function(jqXHR) { // before jQuery send the request we will push it to our array
        $.xhrPool.push(jqXHR);
    },
    complete: function(jqXHR) { // when some of the requests completed it will splice from the array
        var index = $.xhrPool.indexOf(jqXHR);
        if (index > -1) {
            $.xhrPool.splice(index, 1);
        }
    }
});

Simple and useful.

Note: If the request has already been sent to the server then the server will process the request even if we abort the request but the client will not wait for/handle the response.

PS. And how to terminate all ajax requests when we using backbone.js? Stay tuned, I'm preparing the article.

PPS. Thanks for reading my blog/rss ;)


blog comments powered by Disqus