Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up ajax time out?

I have this code to time out ajax call after 40 secs:

if (xmlhttp) {
    xmlhttp.open("GET", MY_SERVLET, true);              xmlhttp.onreadystatechange = showResults;               
    xmlhttp.send(null);
    var httpTimeOut=setTimeout("ajaxTimeout();",40000);
            }

        function ajaxTimeout() {
            xmlhttp.abort();
        document.getElementById('errorShow').innerHTML = "Request Timed out";
            }

However I am unable to test this due to environment constraints at my place. Can anyone please tell if this is correct or any modifications are required??

like image 441
buzz3110 Avatar asked Oct 15 '25 08:10

buzz3110


1 Answers

Should fix that:

if (xmlhttp) {
    xmlhttp.open("GET", MY_SERVLET, true);
    xmlhttp.onreadystatechange = showResults;               
    xmlhttp.send(null);
    setTimeout(function() {  xmlhttp.abort()  },40000);

since ajaxTimeout function can't "see" xmlhttp variable, but we can use anonymous function to have access to local variables.

Yet another approach is to use jQuery.ajax so the library would take care of it.

Your code would look like so:

$.ajax({
    url: MY_SERVLET,
    async: true,
    timeout: 40000,
    success: function(args) { 
        // on success code
    }
})
like image 170
Nemoden Avatar answered Oct 17 '25 15:10

Nemoden