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>

1

1 Answer 1

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

ah... that's what I wasn't getting. thanks jack. could you please explain why the send() is after onreadystatechange()?
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.