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

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,254 Points

AJAX Problem. Won't recognise the HTML on my page.

Hello Treehouse folk.

I've got something of a mystery on my hands here! I have a simple AJAX request based on Dave's example in the first stage of the course. It's just pulling in the same sidebar.html page.

I put it on my website as an addon domain but I don't see why that should be an issue as it's the same server.

Anyway here's my script.

<script>

        //create a variable named xhr and assign it a new XMLHttpRequest object.
        var xhr = new XMLHttpRequest();

        //Open the Ajax Request using GET method and point to file on server
        xhr.open('GET', 'sidebar.html');

        //callback function of AJAX Request
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                document.getElementById('ajax').innerHTML = xhr.responseText;
            }
        };

        xhr.send();

    </script>

And I get this response from the console.

Uncaught TypeError: Cannot set property 'innerHTML' of null

It doesn't seem to like innerHTML for some reason. It's not so much a problem with sending the request as that logs just fine but the HTML doesn't display.

Any ideas? http://www.jonniegrieve.co.uk/jg-lab.co.uk/ajax.html

1 Answer

In your code you're assigning the content from the sidebar that you are loading to an element with the id of ajax. the error you get is because you're trying to add innerHTML to a none existing element.

add the id to something like:

    <p id="ajax"></p>

hope this helps.

Jonathan Grieve
Jonathan Grieve
Treehouse Moderator 91,254 Points

With your help, I've finally worked it out. :D

I put the id on the section element thinking that is what was looking for.

Then I did what you said on the ajax.html page and voila lol Thank you!

I'll have to check out the workspace code on the video as I was sure I was following the video to the letter but perhaps not.

Awesome, glad I could help. You did everything right on the js side you were only missing the id on the html element to inject the content into.