Reputation: 2328
I am trying to call an ajax request again after the internet failure.
Can anyone help me with this? Here is my code.
var loadAgain = function(){
$.ajax({url: 'URL',
success: function(result){
alert('Success');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.readyState == 0) {
alert('No internet connection');
setTimeout(loadAgain, 500);
}
else {
alert('Other Issue');
}
}
});
}
Edited: I have seen another option but I want to recall the ajax on internet disconnect.
Upvotes: 0
Views: 256
Reputation: 1372
The only issue is your check of readyState
when you should actually be checking for a status code. Once a request is fired off, readyState
will never equal 0
, even if it fails (source).
Here's what your code should look like:
function loadAgain(){
$.ajax({
url: 'URL',
success: function(){
console.log('Success');
},
error: function(event) {
if (event.statusCode === 0) {
console.error('No internet connection');
setTimeout(function(){
loadAgain();
}, 500);
}
else {
// do something else...
}
}
});
}
Also, I replaced your alerts with console statements. Get into the habit of using those, they're much easier to debug (see this SO answer).
Upvotes: 1