JavaScript AJAX Basics (retiring) Programming AJAX Processing JSON Data

Nicklas Augustine
Nicklas Augustine
8,383 Points

Why use readyState === 4 at all?

I cannot understand why it is wise to check for .readyState === 4? Why not just check if .status === 200 and then have the callback function running?

1 Answer

Seth Kroger
MOD
Seth Kroger
Treehouse Moderator 56,314 Points

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState

A readyState of 2 means, "send() has been called, and headers and status are available." In other words, if it is a successful response, the status code will be 200 but you haven't received and data in the body yet (or only partial data if readyState is 3) and still need to wait for it to come in.

Seth Kroger : (I know this is a pretty old reply) So Seth if I'm understanding you correctly, we use xhr.readyState === 4 over status ===200 because the readyState is in a different (earlier) part of the send/receive data sequence so it'll catch more issues than status ===200? Or can you elaborate more? I still struggle to understand Mozilla Developer Network for now.

Seth Kroger
Seth Kroger
Treehouse Moderator 56,314 Points

Not necessarily issues but you usually want the callback to process the data you received, and that isn't guaranteed to be there or be complete until then.