5

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.

9
  • 3
    JavaScript can't log requests aren't made through AJAX; therefore, this can't be done. Additionally, there is no built-in object or variable that could have this. Commented Jan 7, 2016 at 22:50
  • 4
    I'm voting to close this question as off-topic because what OP is asking is not possible Commented Jan 7, 2016 at 22:52
  • 2
    if you use some framework, you can display a variable $statusCode in your template, and in the controller (or php code or whatever) you get $statusCode = $this->response->getStatusCode(); Commented Jan 7, 2016 at 22:52
  • @PierreEmmanuelLallemant You're still making a request, which is not what OP asked for. Commented Jan 7, 2016 at 22:52
  • @ArcaneCraeda: there is always one request to load the page, it's what he is speaking about. Commented Jan 7, 2016 at 22:53

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

There is a way to do this reliably with a webworker. But it assumes you've loaded the page at least once before so that you installed the webworker, after that you can intercept all the requests and their status code, the only annoying part is that it doesn't work for the first page load but you could ask it to reload the page straight away after install to mitigate this issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.