Categories
ajax javascript jquery

Abort Ajax requests using jQuery

1944

Is it possible that using jQuery, I cancel/abort an Ajax request that I have not yet received the response from?

2

  • 2

    Maybe I’ve misunderstood the question, but couldn’t you simply use $.ajaxStop?

    Sep 13, 2013 at 11:47

  • 17

    @LukeMadhanga; I think ajaxStop only detects when all AJAX requests are complete, it doesn’t stop a request. In my experience, you would use it like this: $(document).ajaxStop(function(){alert("All done")}). Using .abort() is the best option.

    – TheCarver

    Dec 9, 2013 at 11:35


1830

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.

0

    123

    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.

      80

      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.

      1

      • 55

        In this context, asynchronous simply means the request doesn’t interrupt the flow of the script. Browsers now have the ability to abort the request prematurely before the request is completed.

        Apr 10, 2012 at 19:12