Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
Seth Kroger
56,413 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
56,413 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.