Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to get the HTTP status code from within the $.ajax.error method?

Tags:

jquery

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');         }     }, }); 

Update:

@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?

like image 622
Andrew Avatar asked Jul 14 '11 22:07

Andrew


People also ask

How can I get HTTP status code?

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.


1 Answers

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.

like image 113
Alex Reynolds Avatar answered Sep 23 '22 13:09

Alex Reynolds