2

I am learning about AJAX and am trying to get the contents of my file "info.txt" to be displayed inside a div with id "demo". However it keeps returning blank. Unfortunately, in order to test this you would have to try this code on an actual server (which I am) and have to supply your own "info.txt" file. I please supply a standard javascript answer (non-JQuery), please!

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.open("GET", "info.txt", true);
  xhttp.send();
  document.getElementById("demo").innerHTML = xhttp.responseText;
}
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
Govind Rai
  • 14,406
  • 9
  • 72
  • 83
  • 3
    Your problem is the first "A" in AJAX, meaning it is asynchronous. You have to register a callback to handle the response. Look here for a start: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started – Quagaar Dec 23 '16 at 22:44

1 Answers1

2

The true you're passing to xhttp.open is saying your request is async, which means it's not going to wait for the response.

You need to either remove that true (unrecommended) or properly set a callback for when the response is received:

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.open("GET", "info.txt", true);
  xhttp.onreadystatechange = function () {
    if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) {
      document.getElementById("demo").innerHTML = xhttp.responseText;
    }
  };
  xhttp.send();
}
Jack
  • 20,735
  • 11
  • 48
  • 48
  • ah... that's what I wasn't getting. thanks jack. could you please explain why the `send()` is after `onreadystatechange()`? – Govind Rai Dec 23 '16 at 23:03
  • 1
    @GovindRai because you're defining a callback with `onreadystatechange` that runs _when_ any changes happen...or in this case there's if to check if it's complete (`DONE`). An easy/simplified way to think of this is if you're asking someone to go to the store for you, and do something with the stuff. You're going to tell them what you want (`open`) and what do with it when they get back (`onreadystatechange`) _before_ you send (`send`) them on their way to the store. – Jack Dec 23 '16 at 23:11