Link to home
Start Free TrialLog in
Avatar of Rohit Bajaj
Rohit BajajFlag for India

asked on

Detecting if ajax call errored out due to either server down or network not there

Hi,
I am making an ajax call like :
$.ajax({
            type: 'POST',
            contentType: 'application/json',
            url: postURL,
            data: JSON.stringify(objectTobeSent),
            success: function(note, status, xhr) {
                
                
            },
            error: function(request, status, error) {
                var responseText = request.responseText;
                $('.error_message').text(responseText);
                $('.error_message').show();
            }
        });
    });

Open in new window

I stopped the server that serves this request. And so when this ajax call was executed it errored out.
I found that in such cases request.readyState value is 0. But unsure whether this is always the case.

will putting a check for this is fine if i want to detect that there was some problem establishing connection ?
Also on https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
it states that UNSENT means that client has been created and open() is not yet called.
what happens when open() is called and why in case of internet not there or server is down its throwing readyState as 0 ? why cannt it call open ?? does open establishes a connection with the server ? and state is sent to OPENED only when the connection is established properly  ?


Thanks
Avatar of Swatantra Bhargava
Swatantra Bhargava
Flag of India image

By calling $.post that way, you automatically pass only in a success handler function.

If something on the request went wrong, this method is not even executed.

To have more control either use $.ajax() directly, or pass in fail handlers. That could look like

$.post("page.php", {data: stuff}, function(data, status) {
   // we're fine here
}).fail(function(err, status) {
   // something went wrong, check err and status
});
The same thing using .ajax():

$.ajax({
   type: 'POST',
   url: 'page.php',
   data: stuff,
   success: function( data ) {
   },
   error: function(xhr, status, error) {
      // check status && error
   },
   dataType: 'text'
});
Avatar of Rohit Bajaj

ASKER

I am using $.ajax here . I want to understand what each readyState means
ASKER CERTIFIED SOLUTION
Avatar of Swatantra Bhargava
Swatantra Bhargava
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial