How to cancel an HTTP request using javascript

I have a page on which an event handler is attached to an onclick event. when the event fires, it passes the contents of the text field to the GET request. since the url is not in the same domain , so i create a script tag and attach the url to its source like this

 elem.onclick=fire; function fire() { var text=document.getElementById('text').value; var script=document.createElement("script"); script.className="temp"; script.src="some url"+"?param="+text; document.body.appendChild(script); } 

now if this event is fired and more than once I want to cancel all previous GET requests (since they can still receive a response) and make the GET request the last text. But for this I need to cancel the previous requests. I tried

 document.body.removeChild(script); script.src=null; 

but it doesn’t work in Firefox (I use Firefox 5 ), although it works in Google Chrome . Does anyone know if these requests can be canceled in Firefox, and if so, how?


UPDATE As suggested by Alfred, I used window.stop to cancel the request, but did not cancel the request, but hung. This means that when I look in firebug, it looks like the request is being executed, but there is no answer.

+7
source share
5 answers

The solution is simple: use <img> instead of <script> to create HTTP requests. Also you always need to change the src attribute of the element the same .

 var img; function fire() { var text = document.getElementById('text').value; var im = img || (img = new Image()); im.src = "url"+"?param="+text; } 

You can make sure that it really works by doing the following: the URL you are requesting should have a huge response time (you can provide this using, for example, the PHP sleep function). Then open the Net tab in Firebug. If you press the button several times, you will see that all outstanding requests are aborted.

+4
source

This is completely removed from the hip, but if the script tag has not finished loading, perhaps just script.parentElement.removeChild( script ) . This is more or less what mootools does anyway. (Technically, they first replace /\s+/ with ' ' , but that doesn't seem to be very important).

+2
source

I'm not sure if this is what you are looking for, but it seems like a similar problem: http://www.velocityreviews.com/forums/t506018-how-to-cancel-http-request-from-javascript.html

+1
source

Can I use the JS infrastructure? If so, MooTools has this functionality built into the Request.JSONP object

+1
source

To get around the cross-domain access issue, you can probably use CORS (assuming you can change what is on the server): http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with- cors /

If you do, you can use the more standard XMLHttpRequest abort () undo function.

CORS is compatible with all major modern browsers except Opera (http://caniuse.com/cors).

0
source

All Articles