Aborting XMLHttpRequest on Timeout

Tuesday, June 17, 2008

When your application is using ajax, there are possibilities that you made many HTTP request at a time, especially if you have a page with multiple ajax components or what they call mashup. And that might be a problem. You have to know whether your request has been done or not.

The simplest way to do it is by defining a timeout period for the request, if a request takes longer time than the period defined, then you have to abort the request, and rolling back the condition to before the request is sent(if any).

The method used here is abort(), XMLHttp.abort(). The following code will show you how to abort the request if it has not been fully executed after 7 seconds. The file sleep.php here is only a dummy file which took 10 seconds to execute, therefore the request will be aborted for sure.

Here's the code for the sleep.php file

<?php
sleep(10);
echo "this text only appeared after 10 seconds";
?>

And here's the html file with a code to abort the request if it took longer than 7 seconds

<script language="JavaScript" type="text/javascript">
function getXMLHttp() {
 var XMLHttp = null;
 if (window.XMLHttpRequest) {
   try {
     XMLHttp = new XMLHttpRequest();
   } catch (e) { }
 } else if (window.ActiveXObject) {
   try {
     XMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
   } catch (e) {
     try {
       XMLHttp = new ActiveXObject(
         "Microsoft.XMLHTTP");
     } catch (e) { }
   }
 }
 return XMLHttp;
}

var XMLHttp = getXMLHttp();
XMLHttp.open("GET", "sleep.php");
XMLHttp.onreadystatechange = function() {
 if (XMLHttp.readyState == 4) {
   window.alert("Returned data: " +
                XMLHttp.responseText);
 }
}
XMLHttp.send(null);
window.setTimeout("timeout();", 7000);

function timeout() {
 if (XMLHttp.readyState != 4 &&
     XMLHttp.readyState != 0) {
   XMLHttp.onreadystatechange = function() { };
   XMLHttp.abort();
   window.alert("Request aborted");
 }
}
</script>
Wait until 7 seconds and a javascript alert will tell you that request is aborted.

Hope this helps.

0 comments: