Retry jQuery ajax request

I am making an ajax request to the server. And sometimes I get error 502. So, if it is called by the error () method, it is called.

How can I repeat the request if you receive an error message? The code should look like this:

$.ajax({ url: 'http://server/test.php', type: 'GET', dataType: 'jsonp', cache: 'false', timeout: 32000, success: function(data) { //some actions here }, error: function(jqXHR, textStatus, errorThrown) { console.log("Error[refresh]: " + textStatus); console.log(jqXHR); // here I want to repeat the request like "this.repeat()" }, }); 
+4
source share
3 answers

you can do it like this:

 function ajaxCall(){ $.ajax({ url: 'http://server/test.php', type: 'GET', dataType: 'jsonp', cache: 'false', timeout: 32000, success: function(data) { //some actions here }, error: function(jqXHR, textStatus, errorThrown) { console.log("Error[refresh]: " + textStatus); console.log(jqXHR); ajaxCall(); // recursion call to method. }, }); } 
+6
source

Put your code in a function and call that function again. as:

 function ajaxFunction() { .... error:function(){ajaxFunction();} } 
+5
source

With a call limit, as suggested by Hadas:

 function ajaxCall(count) { count = typeof count == 'undefined' ? 0 : count; limit = 5; if(count === limit) return; // no need to specify cache and type: // type has 'GET' as default value // cache has default value of false if the dataType is jsonp $.ajax({ url: 'http://server/test.php', dataType: 'jsonp', timeout: 32000, async: false }).done(function(data) { // some actions here }).fail(function(jqXHR, textStatus, errorThrown) { count += 1; console.log("Error[refresh]: " + textStatus); console.log(jqXHR); // 500, 1000, 1500, 2000 etc setTimeout(function() { ajaxCall(count); }, 500*count); }); }; 
+3
source

Source: https://habr.com/ru/post/1392306/


All Articles