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 AJAX Callbacks

AJAX Callbacks, it loops

So I have workspaces open and I am coding along with Dave McFarland, i have added in my conditional code to check for anything other than a server response of 200. It should try to load missing.html and return an alert of 404: file not found. Instead it fires off and returns index.html inside of index.html and then the second time you attempt to fire off the request it tells me

Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED. (index):30
sendAJAX (index):30
onclick (index):1

Here it my AJAX

    //create XMLHttpRequest Object
    var xhr = new XMLHttpRequest();

    //create a callback funtion
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          document.getElementById('ajax').innerHTML = xhr.responseText;
        } else {
          alert(xhr.statusText);
        }

      }
    };

    //open the AJAX request
    xhr.open('GET', 'missing.html');

    //send off AJAX request
    function sendAJAX(){
      xhr.send();
      document.getElementById('load').style.display = "none";
    };

its being fired by this line of HTML

<button id="load" onclick="sendAJAX()">Brint it!</button>

Update: If I call sidebar.html instead of missing.html it loads as intended. If I target missing.html is should return xhr.status === 404 (other than 200) ergo return an alert, however it doesn't, it instead load index.html inside of index.html.

2 Answers

Joseph Greevy
Joseph Greevy
4,990 Points

I would try putting the xhr.open() Inside your function like so

function sendAJAX(){
      xhr.open('GET', 'missing.html');
      xhr.send();
      document.getElementById('load').style.display = "none";
    };

Yeah I tried that and it still loops and displays index.html inside of index.html; the first time you click the button, every click after that the the console in dev tools says it finished loading 'missing.html' (there isn't a missing.html)

Donald Wilson
Donald Wilson
5,418 Points

try putting in the sidebar.html file instead of the missing.html file and see if that produces any results.

// open the AJAX request xhr.open('GET', 'sidebar'); document.getElementById('load').style.display = "none"; };