JQuery.ajax () - What is the best way to handle timeouts?

I am wondering what is the best way to handle timeouts using jQuery.ajax () . This is my solution at the moment: if a timeout occurs, the page will reload, and the script will get another chance to load data within the specified timeframe.

Problem : if "get_json.php" (example below) is really unavailable, it will become an infinite reload cycle. Possible solution: add a counter and cancel after rebooting $ x.

Question 1 : What is the best way to deal with a timeout error?

Question 2 : What is your recommended timeout for a timeout and why?

The 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!

+7
source share
1 answer

You can do it differently, first you can clear the interval when a timeout occurs. If you use this function clearInterval() , than you do not need to reload the page. It will 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); 
+4
source

All Articles