I\'m using jQuery to make an AJAX request. I want to perform different actions whether or not the HTTP status code is a 400 error or a 500 error. How can I achieve this?
You should create a map of actions using the statusCode
setting:
$.ajax({
statusCode: {
400: function() {
alert('400 status code! user error');
},
500: function() {
alert('500 status code! server error');
}
}
});
Reference (Scroll to: 'statusCode')
EDIT (In response to comments)
If you need to take action based on the data returned in the response body (which seems odd to me), you will need to use error:
instead of statusCode:
error:function (xhr, ajaxOptions, thrownError){
switch (xhr.status) {
case 404:
// Take action, referencing xhr.responseText as needed.
}
}