views:

13549

answers:

5

How do I cancel an ajax request that I have not yet received the response from using jquery?

+1  A: 

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.

tvanfosson
+2  A: 

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.

Yuval A
+52  A: 

Most of the jQuery ajax methods return an XMLHttpRequest (or ie equivalent) object, so you can just use abort()
msdn docs
MDC docs

var x = $.ajax({
    type: "POST",
    url: "some.php",
    data: "name=John&location=Boston",
    success: function(msg){
       alert( "Data Saved: " + msg );
    }
});

//kill the request
x.abort()
meouw
Can you please elaborate on what abort() exactly does?
Yuval A
@Yuval, https://developer.mozilla.org/en/XMLHttpRequest#abort()
J-P
It's like clicking the 'stop' button on your browser. It cancels the request. You can then reuse the same XHR object for another request.
meouw
Of note, if the server has already received the request, it may continue processing the request (depending on the platform of the server) even though the browser is no longer listening for a response. There is no reliable way to make the web server stop in its tracks with processing a request that is in progress.
Erv Walter
Awesome, thanks I was also looking for such an option like this :Puhh
Braveyard
I used this approach to solve a problem I was having with opening new windows, making ajax calls, and I believe, eventually using up the allowable connections. This was an issue with IE8, not other browers. I found that using code exactly as suggested by meouw resulted in my ajax request being terminated before I got the response I needed. I solved this by specifying async:false. This was fine in my case since the user shouldn't do anything without the server response, but obviously async not sync is the intention of ajax. Perhaps there is a way to do this abort without losing response?
Carvell Fenton
If the request is aborted after the server receives the request but before the response is returned, is the success function still called?
brad
A: 

meouw's solution is correct, but if your are interested in more control then you could try the ajaxManager plugin for jQuery.

Prestaul
A: 

Superb solution abort() is working .... jQuery is awesome ... ibrahim ,Hyderabad INDIA