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
4,194 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,411 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