Skip to content
Advertisement

how to detect a server error into a jquery ajax call?

I use Jquery to parse an json from url: the code is like this:

function fetchdata() {
var statusUrl = '/api/desk/j/';
$.ajax({
    url: statusUrl,
    dataType: "json",
    type: 'post',
    success: function(response) {
        alert('ok');
    },
    error: function(xhr, status, error) {
        var err = JSON.parse(xhr.responseText);
        alert(err.message);
    }
});

}

everything works fine, but if the server is not reachable I’m not able to detect it: I tried to do something in error: function, but seems that the code in error is fired only if the json has an error

have you got some ideas?

thank you!

Advertisement

Answer

You need to test the statusText from the jQuery textStatus response object. You can take advantage of your browser’s developer console to inspect this object. You can expand the properties and methods for your perusal, however you wanna use it. Just click on the returned message of the console.log() to see these properties and methods that you wan’t to use for error detection.

function fetchdata() {
  var statusUrl = '/api/desk/j/';
  $.ajax({
    url: statusUrl,
    dataType: "json",
    type: 'post',
    success: function(response) {
      alert('ok');
    },
    error: function(textStatus) {
      console.log(textStatus);
      console.log(textStatus.statusText, textStatus.status);
    }
  });
}
fetchdata();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement