Angelin Nadar
Angelin Nadar

Reputation: 9300

Why do we check for both xmlHttpObj.readyState =4 and xmlHttpObj.status = 200?

Why do we check for both

xmlHttpObj.readyState =4 

and

xmlHttpObj.status = 200 

not just

 xmlHttpObj.readyState =4 

Upvotes: 0

Views: 1027

Answers (2)

Angelin Nadar
Angelin Nadar

Reputation: 9300

In many Ajax applications, you'll see a callback function that checks for a ready state and then goes on to work with the data from the server response.This turns out to be a short-sighted and error-prone approach to Ajax programming. If a script requires authentication and your request does not provide valid credentials, the server will return an error code like 403 or 401. However, the ready state will be set to 4 since the server answered the request (even if the answer wasn't what you wanted or expected for your request). As a result, the user is not going to get valid data and might even get a nasty error when your JavaScript tries to use non-existent server data.It takes minimal effort to ensure that the server not only finished with a request, but returned an "Everything is OK" status code. That code is "200" and is reported through the status property of the XMLHttpRequest object.

To make sure that not only did the server finish with a request but that it also reported an OK status, add an additional check in your callback function of xmlHttpObj.status = 200

Upvotes: 0

Ry-
Ry-

Reputation: 224952

A readyState of 4 means that the request is complete, but a status of 200 means the request was a success. 400 and higher is an error (404 = Not found, 500 = Internal Server Error for example).

Upvotes: 1

Related Questions