Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript AJAX Basics (retiring) AJAX Concepts A Simple AJAX Example

Why is so imporant put number 4 for simple AJAX I.E. (xhr.readyState === 4) ?

I am not sure strict function have to be "four" where these came from? Is because the letters of getElementById('ajax'); ?

<!DOCTYPE html>
  <meta charset="utf-8">
  <link href='http://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="css/main.css">
  <title>AJAX with JavaScript</title>
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'sidebar.html');
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      document.getElementById('ajax').innerHTML = xhr.responseText;

  function sendAJAX() {
    document.getElementById('load').style.display = 'none';
  <div class="grid-container centered">
    <div class="grid-100">
      <div class="contained">
        <div class="grid-100">
          <div class="heading">
            <h1>Bring on the AJAX</h1>
          <button id="load" onclick="sendAJAX()" class="button">Bring it!</button>
          <ul id="ajax">


there you go http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp

the answer is 4: request finished and response is ready

2 Answers

Jonathan Grieve
Jonathan Grieve
Treehouse Moderator 90,705 Points

Because each time you make an AJAX request it has to pass 4 stages. If you get to stage 4 then you've successfully made the request. The code is simply a way to check that we've reached stage for of the ready state. :-)

Jason S
Jason S
16,247 Points

3: processing request the code works if you change the 4 to a 3 so does that mean it works when it's processing?

Jonathan Grieve
Jonathan Grieve
Treehouse Moderator 90,705 Points

Personally I'd still with the 4 because once you get there, you know you've got passed any problems with server or processsing. :-)

Joshua Briley
Joshua Briley
Courses Plus Student 24,645 Points

I was hoping I wasn't the only one who didn't understand this. Thanks for asking it!