javascript - Abort Ajax requests using jQuery

ID : 476

viewed : 311

Tags : javascriptjqueryajaxjavascript





Top 5 Answer for javascript - Abort Ajax requests using jQuery

vote vote

91

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.

vote vote

87

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.

vote vote

71

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.

vote vote

64

Save the calls you make in an array, then call xhr.abort() on each.

HUGE CAVEAT: You can abort a request, but that's only the client side. The server side could still be processing the request. If you are using something like PHP or ASP with session data, the session data is locked until the ajax has finished. So, to allow the user to continue browsing the website, you have to call session_write_close(). This saves the session and unlocks it so that other pages waiting to continue will proceed. Without this, several pages can be waiting for the lock to be removed.

vote vote

56

AJAX requests may not complete in the order they were started. Instead of aborting, you can choose to ignore all AJAX responses except for the most recent one:

  • Create a counter
  • Increment the counter when you initiate AJAX request
  • Use the current value of counter to "stamp" the request
  • In the success callback compare the stamp with the counter to check if it was the most recent request

Rough outline of code:

var xhrCount = 0; function sendXHR() {     // sequence number for the current invocation of function     var seqNumber = ++xhrCount;     $.post("/echo/json/", { delay: Math.floor(Math.random() * 5) }, function() {         // this works because of the way closures work         if (seqNumber === xhrCount) {             console.log("Process the response");         } else {             console.log("Ignore the response");         }     }); } sendXHR(); sendXHR(); sendXHR(); // AJAX requests complete in any order but only the last  // one will trigger "Process the response" message 

Demo on jsFiddle

Top 3 video Explaining javascript - Abort Ajax requests using jQuery







Related QUESTION?