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

Peter Flynn
Peter Flynn
7,756 Points

Why did we check to see if the readyState equals to 4 ?Does it matter what number we use in this case?

Why did we use the number 4 instead of another number? Why 4?

2 Answers

Richard Hope
Richard Hope
25,237 Points

Ajax after making an ajax call the readyState will change depending on the progress of the request:

0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready

It is only when readyState equals 4 that you can do something using the response from the call

Just to comment, I'm annoyed that Dave didn't explain this in the video, as now I know that number isn't arbitrary and actually rather important.

Yes. I am also annoyed that this wasn't explained in the video by Dave.

Ronnelle Torres
Ronnelle Torres
5,958 Points

I just started doing AJAX. I thank you for posting the exact question that I had in mind. I hate that he didn't explain why he used number 4 instead of other numbers.

If Dave had explained this, the video would β€” by definition β€” be more thorough. However, having to read through this thread will definitely make the information stick. Learning is a beast! Plus, Dave does explain this in the AJAX Callbacks video found in the next stage.

Kaitlyn Threndyle
Kaitlyn Threndyle
18,204 Points

Basically, the numbers 0 - 4 represent the state of the request to the server.

0 = unsent, 1 = opened, 2 = received, 3 = loading, 4 = done

In this case we need to wait for the server to finish and send the response back before we can use that info to update the html. That's why we use readyState === 4 .