Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.ajax() - How to handle timeouts best?

I'm wondering, what's the best way to handle timeouts with jQuery.ajax(). That's my solution at the moment: If an timeout occurs the page will be reloaded and the script gets another chance to load the data within it's given timeframe.

Problem: if "get_json.php" (example below) is really not available, it will become an endless reloading-loop. Possible solution: adding a counter and cancel after $x reloads.

Question 1: How to handle the timeout error best?

Question 2: What's your recommended timeframe for a timeout and why?

Code:

$.ajax({
    type: "POST",
    url: "get_json.php",
    timeout: 500,
    dataType: "json",
    success: function(json) {
        alert("JSON loaded: " + json);
    },
    error: function(request, status, err) {
        if (status == "timeout") {
            // timeout -> reload the page and try again
            console.log("timeout");
            window.location.reload();
        } else {
            // another error occured  
            alert("error: " + request + status + err);
        }
    }
});

Thanks in advance!

like image 717
Mr. B. Avatar asked Jun 17 '13 20:06

Mr. B.


People also ask

What is the default timeout for jQuery AJAX?

The default value is 0. Which means there is no timeout. Return value – The ajax timeout option does not return any value.

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.

How do you call AJAX every 5 seconds?

Creating a function that calls the AJAX request and using this function in setInterval() and set Interval for 5 sec. Now the function executes every 5 seconds and fetches new data from the server. It repeatedly executes the function even when the previous AJAX request is not successfully executed and return.


1 Answers

You can do it other way, you can clear interval first when timeout occured. If you use this clearInterval() function than you won't need to reload page. It'll stop automatically.

function ajax_call(){ 
$.ajax({
        type: "POST",
        url: "get_json.php",
        timeout: 500,
        dataType: "json",
        success: function(json) {
            alert("JSON loaded: " + json);
        },
        error: function(request, status, err) {
            if (status == "timeout") {
                // timeout -> reload the page and try again
             clearInterval(ajax_call);
                window.location.reload(); //make it comment if you don't want to reload page
            } else {
                // another error occured  
                alert("error: " + request + status + err);
            }
        }
    });
}

setInterval(ajax_call,timeout_duration);
like image 90
Ghanshyam Katriya Avatar answered Oct 03 '22 06:10

Ghanshyam Katriya