Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.get/$.ajax passes HTTP status code 200 instead of expected status code of 201 or 202

Tags:

jquery

ajax

http

I've a server that returns HTTP status code 200, 201, and 202 from the same url. In Chrome, I've confirmed with the Network debugging panel that the Status Code is what I expect it to be (i.e. 200, 201 or 202). I rely on that status code to determine the next step.

I'd expect that the callbacks for jQuery (version 1.5.2) AJAX requests to set jqxhr.status to the status code that the server sends. However, the status code is always 200, even if the code sent by the server is 201 or 202.

In other words, the following code prints Code: 200 regardless of what the server sends.

$.get(url, {}, function (data, textStatus, xhr ) {
    alert("Code: " + xhr.status);
});

Why is this happening, and more importantly, how can one get the actual status code in a jQuery AJAX callback for $.get or $.ajax?

Thank you for reading.

like image 398
Brian M. Hunt Avatar asked Oct 28 '11 16:10

Brian M. Hunt


1 Answers

From what I have experienced jQuery is just not set up very well for handling actual status codes in the response. You can try just doing a manual AJAX call using some good old bare bones JS and handle the status yourself.

Here are a few tutorials on how to do so.

http://www.degraeve.com/reference/simple-ajax-example.php

http://www.w3schools.com/ajax/default.asp

request.status is where you should be able to access the status code in your request object. Here is another page showing a little bit about how to access even more granular information about the status of the request.

http://www.ibm.com/developerworks/web/library/wa-ajaxintro3/

Hope that helps you nail it!

like image 166
thomallen Avatar answered Nov 04 '22 19:11

thomallen