Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE alternative to window.stop() (cancel all pending requests)

I'm looking for an alternative to window.stop() for IE. I have tried document.execCommand('Stop'), but it doesn't seem to work. I'm trying to cancel a XMLHttpRequest which is called from within a ASP user control i'm using. I can't use jQuery's .abort() since i do not set the request my self.

like image 265
Yasen Yankov Avatar asked Jan 25 '12 16:01

Yasen Yankov


2 Answers

I assume control on the page uses jQuery.ajax and you know when you need to abort the request, under your criteria.

How about something like this?

(function ($) {
    var xhr = null, 
        originalAjax = $.ajax,
        updatedAjax = function (url, options) {
            xhr = originalAjax(url, options);
        };
    $.ajax = updatedAjax;
})(jQuery);

Now you have a variable called xhr which holds the underlying xmlhttp object. You can call abort() on the object when you need to.

The draw back is that variable will be populated for each ajax request done by jQuery, and I would only include this script on that particular page, maybe even reset the ajax when you are done.

I haven't tried this, just an idea, as I have been mocking ajax calls all the time. Some might think that this approach is a little bit drastic!

Hope you find it useful.

like image 75
Hakan Hastekin Avatar answered Oct 20 '22 14:10

Hakan Hastekin


If you have access to the object you can do it with the object's abort() and onreadystatechange event handler. Here is a working example I tweaked from w3schools

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==2){ xmlhttp.abort();}
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","xmlhttp_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

As you can see, the request text is not loaded because it gets aborted.

like image 22
PAULDAWG Avatar answered Oct 20 '22 12:10

PAULDAWG