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) AJAX Concepts A Simple AJAX Example

Joel Stevenson
Joel Stevenson
4,137 Points

Script at the beginning vs at the end

Was just wondering why are we putting the script tag (and code) before the body? Wasnt it best practice to place java script after the body tags? In this lesson he placed it before the body tags, so how is AJAX different? My code actually didn't work until I put the script tags below the body

3 Answers

Sean King
Sean King
5,144 Points

Hi Joel. So, from what I understand, you're asking why the AJAX request did not work when placed inside the HTML <body> tag. In the video and tutorials, you're likely placing the AJAX request within the <head> tags and not in the HTML body. That's not to say they won't work within the body of the HTML.

You can see in this example from the W3C, AJAX requests do work inside the HTML body.

<!DOCTYPE html>
<html>
<body>

<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

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

</body>
</html>

Because HTML is a synchronous language, the element to which you're pointing in the AJAX request don't exist yet in your original method. However, by placing the <script> tags at the end of the body tag, you'll get the proper response. AJAX itself is asynchronous in nature, but it has to have elements to point to for it to work. In other words, placing the requests in the <head> tags or just before the closing <body> tag should solve any issues you'd have.

Dmitry Polyakov
Dmitry Polyakov
4,989 Points

It's just common practice to put your script tag right before a closing body tag.

Joel Stevenson
Joel Stevenson
4,137 Points

Maybe I explained that wrong, in the video the script tag was placed before the opening body tag not the closing. When I placed my script tag before the opening body tag, my script didn't work. Once I put it after the closing body tag, it worked. Wanted to know why the video put it before the opening body tag. Thanks