Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the http status code with javascript?

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.

like image 896
reggaemahn Avatar asked Jan 07 '16 22:01

reggaemahn


People also ask

How can I get status code from Ajax response?

//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();

How do I get my HTTP status code 200?

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.


1 Answers

Just to confirm what's been said in the comments:

  1. 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.

  2. 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.

  3. 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

like image 98
Stephen Thomas Avatar answered Oct 12 '22 22:10

Stephen Thomas