views:

2776

answers:

1

Hi everyone, I'm looking on the web, but documentation is hard to come by. We all know the basic AJAX call using the browser's built-in XMLHttpRequest object (assume a modern browser here):

    var xmlHttp = new XMLHttpRequest();  // Assumes native object

    xmlHttp.open("GET", "http://www.example.com", false);

    xmlHttp.send("");

    var statusCode = xmlHttp.status;
    // Process it, and I'd love to know if the request timed out

So, is there a way that I can detect that the AJAX call timed out by inspecting the XMLHttpRequest object in the browser? Would I be advised to do something like window.setTimeout(function() { xmlHttp.abort() }, 30000);?

Thanks!

-Mike

+6  A: 

UPDATE: Here's an example of how you can handle a timeout:

var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://www.example.com", true);

xmlHttp.onreadystatechange=function(){
   if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      clearTimeout(xmlHttpTimeout); 
      alert(xmlHttp.responseText);
   }
}
// Now that we're ready to handle the response, we can make the request
xmlHttp.send("");
// Timeout to abort in 5 seconds
var xmlHttpTimeout=setTimeout(ajaxTimeout,5000);
function ajaxTimeout(){
   xmlHttp.abort();
   alert("Request timed out");
}

In IE8, You can add a timeout event handler to the XMLHttpRequest object.

var xmlHttp = new XMLHttpRequest();
xmlHttp.ontimeout = function(){
  alert("request timed out");
}

I would recommend against making synchronous calls as your code implies and also recommend using a javascript framework to do this. jQuery is the most popular one. It makes your code more efficient, easier to maintain and cross-browser compatible.

Jose Basilio
As far as I know the timeout event is available in Internet Explorer 8 only.
Ionuț G. Stan
You are correct. I updated my answer to reflect that.
Jose Basilio
José, I've edited your first example a little. One can pass function objects as first argument of setTimeout and setInterval. Hope you don't mind it.
Ionuț G. Stan
Ionut - thank you for the improvement, I didn't think of that when I pasted the code.
Jose Basilio