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

innerHTML in AJAX Stage 2 Challenge

The question deals with adding a DOM element's inner HTML to attach to the server's response to the AJAX request. This is my response, and I don't know why there is an error.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if(xhr.readyState === 4) {
    if(xhr.status === 200) {
    document.getElementById('main').innerHTML = xhr.responseText;
    }
  }else
    alert(xhr.statusText);
  document.getElementById('sidebar').innerHTML = xhr.responseText;
};
xhr.open('GET', 'sidebar.html');
xhr.send();

Got it. I still used the sidebar id to create a different equation to the innerHTML, and deleted the main.

I hadn't seen your comment yet when I posted but glad you figured it out.

3 Answers

Hi nikoxyz,

I think your problem is that you're adding in more code than what the challenge is asking for. You have the correct code for the sidebar element but it's in the wrong spot.

This is all that you should have by the end of task 2: (minus the instructional comment I put in)

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    if(xhr.status === 200) {
      //This is where you set the innerHTML of the sidebar for task 3 and 4
    }
  }
};
xhr.open('GET', 'sidebar.html');
xhr.send();

Then task 3 and 4 has you create this code: document.getElementById('sidebar').innerHTML = xhr.responseText; which you have but you need to put it in the inner if block.

nikoxyz -

I think the error is in your selection of :

document.getElementById('main').innerHTML = xhr.responseText;

I think it should be :

document.getElementById('ajax').innerHTML = xhr.responseText;

Might wanna double check your HTML and make sure you're grabbing the right element.

Hope this helps ! kj

Yes, it turns out that I needed to create that sidebar function after status === 200 condition. At first I put it at the end, but then copied and pasted after the error message popped up.