javascriptajaxbrowser

How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?


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);?


Solution

  • 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.