I am planning on implementing a series of jQuery AJAX calls in my website and would like to develop a function to abort an AJAX call. How can I do this? I read this link already but it doesn't work for me.
Asked
Active
Viewed 3,160 times
3
-
3its a regular request response. you cant stop it in the middle ( gracefully) – Royi Namir May 30 '13 at 13:20
-
Show us your code. How are you using the code on that post? – Jude Duran May 30 '13 at 13:20
-
2Better dup; [Abort Ajax requests using jQuery](http://stackoverflow.com/questions/446594/abort-ajax-requests-using-jquery) – Alex K. May 30 '13 at 13:21
-
you mean stop an ajax call depending on a response from another ajax call? – MaVRoSCy May 30 '13 at 13:21
2 Answers
7
You need to assign your ajax request to variable,
var xhr = $.ajax({
***
});
then call abort()
xhr.abort();

Chamika Sandamal
- 23,565
- 5
- 63
- 86
0
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);

Maxwell
- 1