How can I retrieve the http status code returned from the server (200, 302 etc.) from javascript/jquery?
I am NOT looking to get this from an ajax request. I want to retrieve it on the initial page load and take some custom actions based on the status code.
P.S, The solution doesn't necessarily need to be cross browser. This is for an internal application and so any browser specific solutions would be acceptable.
//your jquery code will be like this: $. ajax({ type: 'POST', url: $url, data: new FormData(this), dataType: 'json', contentType: false, processData:false,//this is a must success: function(response){ $('your_selector'). html(response); } }); //php code will be like this echo '<div>some html code</div>'; die();
The HTTP 200 OK success status response code indicates that the request has succeeded. A 200 response is cacheable by default. The meaning of a success depends on the HTTP request method: GET : The resource has been fetched and is transmitted in the message body.
Just to confirm what's been said in the comments:
It's not possible to do this reliably from the server. The response might not come from the original server, e.g. if there's a cache in between the server and client.
It's not possible to do this reliably using AJAX to re-request the same page. The response to the second request might differ from that of the original request, e.g. if the server returns a not-modified response to the second request.
It's not possible to do this with standard browsers using any known JavaScript API. That's a question that's been asked often. See, for example Accessing the web page's HTTP Headers in JavaScript
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