user556673 user556673 - 7 months ago 180
Javascript Question

How to cancel/abort jQuery AJAX request?

I've an AJAX request which will be made every 5 seconds. But the problem is before the AJAX request if the previous request is not completed I've to abort that request and make a new request.

My code is something like this, how to resolve this issue?

$(document).ready(
var fn = function(){
$.ajax({
url: 'ajax/progress.ftl',
success: function(data) {
//do something
}
});
};

var interval = setInterval(fn, 500);
);

Answer

The jquery ajax method returns a XMLHttpRequest object. You can use this object to cancel the request.

The XMLHttpRequest has a abort method, which cancels the request.
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.

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). we can use this to check whether the previous request was completed.

$(document).ready(
    var xhr;

    var fn = function(){
        if(xhr && xhr.readyState != 4){
            xhr.abort();
        }
        xhr = $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };

    var interval = setInterval(fn, 500);
);

JQUERY 1.5 UPDATE

Since jQuery 1.5 the $.ajax function now returns a jqXHR object. It still provides many of the old XMLHttpRequest properties for backwards compatibility but seems to capitalise the readystate property which breaks compatibility! Anyway the code above needs to be changed to use readyState for it to continue functioning:

$(document).ready(
    var xhr;

    var fn = function(){
        if(xhr && xhr.readyState != 4){
            xhr.abort();
        }
        xhr = $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };

    var interval = setInterval(fn, 500);
);