1

I try to get the HTTP error code in the generic $(document).ajaxError() method. How can I read it out? I found this jQuery: How to get the HTTP status code from within the $.ajax.error method? but I don't manage to adapt it to my function.

JQuery version is 2.1.3.

$(document).ajaxError(function (jqXHR, textStatus, errorThrown) {
    if (jqXHR.statusCode != "500") {
        $("#global-error-wrapper").show();
        $(".global-error-message-inner-text").text(trans("noconnectionerror"));
    }
});
Liam
  • 22,818
  • 25
  • 93
  • 157
Userino
  • 863
  • 7
  • 28
  • Can you post the code that has your `Ajax` call? – Luke T Brooks Oct 25 '17 at 14:52
  • I have many Ajax-Calls methods, so the goal for me was to handle this generically in the ajaxError function. – Userino Oct 25 '17 at 14:55
  • 1
    Try logging the `jqXHR` object and see what's available (`console.log(jqXHR)`). Might reveal where the information you're looking for is. – Nick Oct 25 '17 at 15:01
  • Thank you for your suggestion. I have already checked the object intensively and unfortunately I didn't find any HTTP code. – Userino Oct 25 '17 at 15:05

2 Answers2

3

You are using ajaxError which seems to be a bit different than the ajax event error handler defined in the settings in the link you posted. For ajaxError(), it looks like the first parameter in the callback is the event and the second is the jqXHR object you want. Also it should be jqXHR.status and not statusCode Try the below

$(document).ajaxError(function (event, jqXHR, settings, thrownError) {
    if (jqXHR.status != 500) {
        $("#global-error-wrapper").show();
        $(".global-error-message-inner-text").text(trans("noconnectionerror"));
    }
});
Andrew Lohr
  • 4,830
  • 1
  • 21
  • 36
0

The statusCode object on the jqXHR object in your ajaxError method refers to an object mapping that you can create when you build your ajax call. If you have an idea of what status codes to expect, you could build out this mapping and send it along with your ajax calls which could help you identify what status code was returned:

var statusCodeMapping = {
    404: function() {
        $notFound = true;
    }
}

$.ajax({
  statusCode: statusCodeMapping
});

You could then examine the $notFound object to see if that was the status code returned from your Ajax call:

$(document).ajaxError(function (jqXHR, textStatus, errorThrown) {
    if ($notFound) {
        $("#global-error-wrapper").show();
        $(".global-error-message-inner-text").text(trans("noconnectionerror"));
    }
});

The $notFound object should be global to your script

Luke T Brooks
  • 537
  • 1
  • 7
  • 23