Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Thanks!

-Mike

like image 933
Mike Avatar asked Jun 19 '09 15:06

Mike


People also ask

Does Ajax call timeout?

Session timeout has been a very common feature in Ajax-based web applications. In responsive interface, the programmer needs to delay the ajax request to achieve some task before the response. This can be achieved by using jQuery setTimeout() function.

What is the default timeout for XMLHttpRequest?

The XMLHttpRequest. timeout property is an unsigned long representing the number of milliseconds a request can take before automatically being terminated. The default value is 0, which means there is no timeout.

What is the default timeout for Ajax?

The default value is 0 , which means there is no timeout.


1 Answers

Some of the modern browsers (2012) do this without having to rely on setTimeout: it's included in the XMLHttpRequest. See answer https://stackoverflow.com/a/4958782/698168:

var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () {     if (xhr.readyState == 4) {         alert("ready state = 4");     } };  xhr.open("POST", "http://www.service.org/myService.svc/Method", true); xhr.setRequestHeader("Content-type", "application/json; charset=utf-8"); xhr.timeout = 4000; xhr.ontimeout = function () { alert("Timed out!!!"); } xhr.send(json); 
like image 99
Julien Kronegg Avatar answered Sep 28 '22 04:09

Julien Kronegg