Abort Ajax requests using jQuery
Solution 1:
Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use abort()
.
See the documentation:
- abort Method (MSDN). Cancels the current HTTP request.
- abort() (MDN). If the request has been sent already, this method will abort the request.
var xhr = $.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
UPDATE: As of jQuery 1.5 the returned object is a wrapper for the native XMLHttpRequest object called jqXHR. This object appears to expose all of the native properties and methods so the above example still works. See The jqXHR Object (jQuery API documentation).
UPDATE 2:
As of jQuery 3, the ajax method now returns a promise with extra methods (like abort), so the above code still works, though the object being returned is not an xhr
any more. See the 3.0 blog here.
UPDATE 3: xhr.abort()
still works on jQuery 3.x. Don't assume the update 2 is correct. More info on jQuery Github repository.
Solution 2:
You can't recall the request but you can set a timeout value after which the response will be ignored. See this page for jquery AJAX options. I believe that your error callback will be called if the timeout period is exceeded. There is already a default timeout on every AJAX request.
You can also use the abort() method on the request object but, while it will cause the client to stop listening for the event, it may probably will not stop the server from processing it.
Solution 3:
It's an asynchronous
request, meaning once it's sent it's out there.
In case your server is starting a very expensive operation due to the AJAX
request, the best you can do is open your server to listen for cancel requests, and send a separate AJAX
request notifying the server to stop whatever it's doing.
Otherwise, simply ignore the AJAX
response.