24

I have this code:

$.ajax({ cache: false,
    url: "/Admin/Contents/GetData",
    data: { accountID: AccountID },
    success: function (data) {
        $('#CityID').html(data);
    },
    error: function (ajaxContext) {
        alert(ajaxContext.responseText)
    }
});

I am still confused about the ajaxContext and how to capture 404 return codes. However I have another question. I am reading something about coding with success and fail and no longer using error in the recent versions of jQuery.

So should I change my code to use done and fail. How then could I check for a 404?

Alan2
  • 23,493
  • 79
  • 256
  • 450

2 Answers2

39

Replace your error function as follows...

error:function (xhr, ajaxOptions, thrownError){
    if(xhr.status==404) {
        alert(thrownError);
    }
}
JayTee
  • 1,209
  • 9
  • 15
  • I previously had error: function (jqXHR, textStatus, errorThrown). is ajaxOptions correct. Should it be textStatus? – Alan2 Jun 07 '12 at 12:09
  • Works for me, don't see why not, but willing to be told differently. – JayTee Jun 07 '12 at 12:21
  • 7
    Just want to note that this will not work on cross domain calls. It will fail silently and neither the "complete" or "error" callback parameters will be executed. – Darren Felton Aug 13 '14 at 19:49
  • .fail method is deprecated since jQuery 1.7, you should use .fail now https://api.jquery.com/deferred.fail/ – cymruu Jul 14 '17 at 18:11
4

404 erros will be handled by the anonymous function hooked up to the error property. Anything other than a successful HTTP request to the URL (i.e. 2xx) will trigger the error method. The following will work for your purpose:

error : function(jqXHR, textStatus, errorThrown) { 
    if(jqXHR.status == 404 || errorThrown == 'Not Found') 
    { 
        console.log('There was a 404 error.'); 
    }
}

When they refer to removing the success and error functions in the jQuery documentation, they're referring to those of the jqXHR class, not the properties of $.ajax().

BenM
  • 52,573
  • 26
  • 113
  • 168
  • But is the coding for that anonymous function by JayTee correct? My previous attempt just put a variable ajaxContent in the paranthasis after function. – Alan2 Jun 07 '12 at 12:08
  • The callback function accepts three arguments: the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object. When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." – BenM Jun 07 '12 at 12:13