0

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.

DsRaj
  • 2,288
  • 1
  • 16
  • 26

1 Answers1

1

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).

sheng
  • 1,226
  • 8
  • 17
  • 1
    Status codes are [here](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status) for reference – Liam Sep 14 '18 at 11:29
  • @DivyeshKanzariya Unnecessary bloating for a simple 1-3 line solution. – sheng Sep 14 '18 at 13:09