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 AJAX Concepts A Simple AJAX Example

Ekramy M.Ali
Ekramy M.Ali
17,748 Points

why request.readyState === 4 ? why 4 ?

I don't understand why using the number 4 exactily.

2 Answers

Hey Ekramy M.Ali,

4 is one of the value for the readyState property. The full list of readyState values is:

0 - The request is initialized

1 - The request has been set up

2 - The request has been sent

3 - The request is in process

4 - The request is completed

if( xhr.readyState === 4 ) {
// Run this code
}

The above conditional statement checks, if the value is 4 which means if the request is complete, run the block of code. We can use other values (numbers) too but it will come up as incomplete or get an error whilst processing therefore we rarely use other numbers.

To learn more about this property and how it works, check out this stackoverflow: https://stackoverflow.com/questions/30522565/what-is-meaning-of-xhr-readystate-4

Check out this MDN, great resource: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState

Hope this helps!

Why didn't Dave give us this information. Seems kind of miss informed on that info. Thanks