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

xhr.readystate If Statement Only Works With a Single ='s?

So I followed along the video, but my AJAX text replacement wouldn't work. I ended up narrowing the problem down to the if statement.

//The video shows this syntax, but the if statement never passes.
if(xhr.readystate === 4) {

//Using the below syntax works fine.
if(xhr.readystate = 4) {

Even though I figured out what caused the issue I'm not exactly sure why the code is behaving differently than shown.

I added the entire HTML file contents incase that somehow clarifies something.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <link href='//fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="css/main.css">
  <title>AJAX with JavaScript</title>
  <script>
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if(xhr.readystate = 4) {
        document.getElementById('ajax').innerHTML = xhr.responseText;
      }
    };
    xhr.open('GET','sidebar.html');
    function sendAJAX(){
      xhr.send();
      document.getElementById('load').style.display = "none";
    };
  </script>
</head>
<body>
  <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()">Bring it!</button>
          </div>
          <div id="ajax">
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

1 Answer

The S in readyState is uppercase. It then works as coded in the video.

if(xhr.readystate === 4) { doesn't work because at that point readystate is undefined. undefined compared to 4 returns false.

if(xhr.readystate = 4) { only 'works' in that it evaluates to true. But what is happening is with the assignment, the readystate property is created, assigned a value of 4 and a value of 4 is returned. 4 is truthy so it evaluates to true.

Try adding the following

 var xhr = new XMLHttpRequest();
      console.log(xhr.readystate)
      console.log(xhr.readystate = 4)
      console.log(xhr)

You should see logged

undefined
4
XMLHttpRequest

If you expand XMLHttpRequest you'll see

readyState: 1
readystate: 4

Thanks! New it had to be something simple I was missing.