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

Why won't my simple AJAX request work?

Using MAMP instead of workspaces to experiment in my own project.

JS:

var xhr = new XMLHttpRequest();
xhr.onreadystagechange = function() {
    if(xhr.readyState === 4) {
        // document.getElementById('footer').innerHTML = xhr.responseTest;
        alert("hello");
    }
}
xhr.open('GET', '../footercontent.php');
xhr.send();

index.php

    <footer id="footer">
      <p>Hello, World</p>
    </footer>

footercontent.php

<p>Hello, World via AJAX!</p>

I am noticing this in the console:

https://i.gyazo.com/fe1163b6171d5679ff564dcab91d45be.png

Can't see an alert and not sure on how to debug this in the console. Any suggestions?

James.

1 Answer

This line could be the problem

document.getElementById('footer').innerHTML = xhr.responseTest;

it should be xhr.responseText

but, if your alert isn't going off than something else is going on.

Just noticed the typo. I corrected it and un-commented it and still nothing has happened. The funny thing is that the dev tools console is returning a 200 for the GET which means its doing it successfully however the alert just won't appear?

James.

Solved - Typo on onreadystatechange :P