vote up 10 vote down star
11

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

flag

5 Answers

vote up 26 vote down

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()
link|flag
Can you please elaborate on what abort() exactly does? – Yuval A Jan 15 '09 at 13:04
@Yuval, developer.mozilla.org/en/XMLHttpRequest#abort() – J-P Jan 15 '09 at 13:15
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 Jan 15 '09 at 13:19
3  
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 May 15 at 17:50
Awesome, thanks I was also looking for such an option like this :Puhh – Tarik Dec 20 at 3:08
vote up 2 vote down

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.

link|flag
vote up 1 vote down

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.

link|flag
vote up 0 vote down

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

link|flag
vote up 0 vote down

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

link|flag

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.