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

Using AJAX on Workspaces

I followed the lesson on Treehouse regarding how to use AJAX but the new page isn't displaying? I want to display the content of a new file at the bottom of my page. All of my files are in Workspaces.

The following script is in my Head Section:

<script> var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readystate === 4) { document.getElementById('ajax').innerHTML = xhr.responseText; } }; xhr.open('GET', 'Contact.html'); xhr.send(); </script>

The following script is in the Body Section:

<div id="ajax"> followed by a closing div

Any idea where my mistakes are??

Hi Elizabeth,

I have zero experience using AJAX, hopefully Dave McFarland can help you out here :).

Sorry to be of no help at all.

Craig

1 Answer

You need to create element, which will call function:

<button type="button" onclick="loadDoc()">Change Content</button>

The function requests data from a web server and displays it:

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
     document.getElementById("ajax").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("GET", "Contact.html", true);
  xhttp.send();
}
</script>

Thanks

You are welcome