Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly cancel an outstanding Ajax request that will never complete?

This question is like another, except that one is asked in the context of JQuery, which I don't use.

Ajax code on my page issues a POST every ten seconds. Once in a while -- every ~600 requests -- my client code hangs waiting for a response that will never show up.

The code will time out and re-issue the Ajax request, but first I want to clean up everything about the outstanding request: I don't want to leave any vestigial state around to muck things up later.

What is the right way to cancel the outstanding request so that things get properly tidied up?

Thanks!

like image 516
Pete Wilson Avatar asked Jun 04 '11 13:06

Pete Wilson


People also ask

How do I cancel a pending AJAX request?

Sometimes you might want to cancel the ajax request that is pending from long time or want to cancel request if user accidently clicked submit button. In that cases, so you can just use abort() method. If the request has been sent already, this method will abort the request.

Which of the following methods is used to cancel the XML HTTP request in AJAX?

abort() Method: This method is used to abort or cancel the HTTP request.

What causes AJAX fail?

Many pages send AJAX requests to a server. Because this relies on the cooperation of the server and the network between the client and the server, you can expect these AJAX errors: Your JavaScript program receives an error response instead of data; Your program has to wait too long for the response.


1 Answers

Store a reference to your last AJAX request and abort it when you start the next one.

For instance:

var lastRequest;

setInterval(function() {
    lastRequest.abort(); // abort the last request

    lastRequest = new XMLHTTPRequest(); // and the rest of your XHR code
}, 10000);
like image 107
lonesomeday Avatar answered Sep 27 '22 15:09

lonesomeday