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?
$.ajax({ type: 'POST', url: '/controller/action', data: $form.serialize(), success: function(data){ alert('horray! 200 status code!'); }, error: function(data){ //get the status code if (code == 400) { alert('400 status code! user error'); } if (code == 500) { alert('500 status code! server error'); } }, });
@GeorgeCummins mentioned that it "seemed odd" to work with the response body. This is the first time that I've attempted doing this sort of thing. Is my approach not a best-practice? What would you recommend? I created another StackOverflow question for this here: What response/status code should I send to an AJAX request when there is a user/form validation error?
Just use Chrome browser. Hit F12 to get developer tools and look at the network tab. Shows you all status codes, whether page was from cache etc.
If you're using jQuery 1.5, then statusCode
will work.
If you're using jQuery 1.4, try this:
error: function(jqXHR, textStatus, errorThrown) { alert(jqXHR.status); alert(textStatus); alert(errorThrown); }
You should see the status code from the first alert.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With