user1672517
user1672517

Reputation:

Is checking for both readyState and status necessary in XMLHttpRequest?

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)?!

Upvotes: 3

Views: 2330

Answers (1)

Quentin
Quentin

Reputation: 943615

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) { ... }
}

Upvotes: 1

Related Questions