3

In this discusison, we can see the syntax for handling XMLHttpRequest and guarding against a wrong readyState and status combinations as follows.

if (request.readyState == 4 && request.status == 200) { ... }

I've always been using the conjunctive conditional trusting that both cases were independent allowing for all four combinations of the operational success when contacting a server.

Yesterday, I was thinking and it hit me that I can't explain what they might be. What are they?

  1. All dandy: readyState is done (4) and status is OK (200).
  2. Erroneous communication: readyState is done (4) and status isn't OK (!200).
  3. Not finished yet: readyState isn't done (!4) and status is OK (200).
  4. ?!?!?!?!: : readyState isn't done (!4) and status is OK (!200).

In particular, I don't get how something that's not finished can be both OK and not OK (cases 3 and 4). Shouldn't it always be status OK when not finished yet (or always status not OK)?!

Community
  • 1
  • 1
  • 1
    If you are using a modern browser, consider using the `onload` event rather than `onreadystatechange`. The `onload` event fires when the request has successfully completed, so you don't need to check `readyState`. There is also a corresponding `onerror` event. – monsur Mar 10 '13 at 11:55

1 Answers1

1

I don't get how something that's not finished can be both OK and not OK (cases 3 and 4).

That isn't what you are testing for.

The test is: Is it ready? No? This condition fails.

You don't have:

if (request.readyState != 4 && request.status == 200) { ... }

or

if (request.readyState != 4 && request.status != 200) { ... }

You only care about the state when the request is finished and is OK.

The syntax you have is shorthand for:

if (request.readyState == 4) {
  if (request.status == 200) { ... }
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • So, if `request.status === 200` is only true when `request.readyState === 4` (*null* or *undefined* prior to that, I'm guessing), wouldn't be sufficient to only check the second if-clause? What am I missing? –  Mar 12 '13 at 20:07
  • `status` will have a value once the `readyState` reaches `2`, so your predicate is incorrect. – Quentin Mar 12 '13 at 23:41
  • Oh, that's why. Thanks! I thought I've seen somebody explain that the *status* won't be set until *readyState* reaches the value of four. Perhaps I misunderstood. Greatly appreciate the help => +1! –  Mar 12 '13 at 23:58
  • https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest lists the status numbers and their meanings – Quentin Mar 13 '13 at 00:23