Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to cancel http request using javascript

i have a page on which there an event handler attached to an onclick event. when the event fires it passes contents of a textbox to a GET request. since the url is not in the same domain so i create a script tag and 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 that event is fired and more than one time i want to cancel all the previous GET request(because they still might be receiving response) and make the GET request with latest text. But for this i need to cancel the previous requests. i tried

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

but this does not work in Firefox(i am using Firefox 5) although this works in Google Chrome.Does anyone know if these requests can be cancelled in Firefox and if yes then how?


UPDATE As suggested by Alfred, i used window.stop to cancel a request but does not cancel a request but hangs it up. It means that when i look into firebug it looks like the request is being made but there is no response.

like image 352
lovesh Avatar asked Jul 28 '11 20:07

lovesh


2 Answers

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

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

You may ascertain that it actually works by doing the following: the URL you request should have a huge response time (you can ensure this using e.g. PHP's sleep function). Then, open Net tab in Firebug. If you click the button multiple times, you'll see that all incomplete requests are aborted.

like image 185
duri Avatar answered Oct 07 '22 19:10

duri


This is entirely shooting from the hip, but if the script tag has not finished loading you can probably simply script.parentElement.removeChild( script ). That is more or less what mootools does anyway. (Technically, they replace /\s+/ with ' ' first, but that does not seem to be terribly important).

like image 34
cwallenpoole Avatar answered Oct 07 '22 17:10

cwallenpoole