Question on create simple ajax javascript call

Whats the best way to put together a simple webpage that contains a javascript code that calls an ajax function to retrieve some data and finally display that data in the simple webpage.

currently I only have

<!DOCTYPE html>
<html>
<body>

<div id="demo">
<h2>AJAX Text</h2>
<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>

You appear to have a working example that fulfills all your criteria.

but where can i pull another file from if i replace ajax_info.txt… where is that coming from. thank you

That file is in the same folder on your server as the web page you are calling the Ajax script from.

You can replace "ajax_info.txt" with any web-accessible file on your domain.You can also call external APIs etc, as long as they are configured to respond to cross-site requests.

Last question, How would I add error handling to this?


<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", "text.txt", true);
  xhttp.send();
}
</script>

If you are set on using XMLHttpRequest you can listen for an error event.

xhttp.addEventListener("error", transferFailed);

function transferFailed(e) {
  console.log("An error occurred while transferring the file.");
  console.error(e);
}

See:

However, assuming you don’t have to support legacy browsers, I would be tempted to use the fetch API instead.

I must admit that the Fetch API is a pleasing thing to use.

function loadDoc() {
  const getText = (response) => response.text();
  const updateDemo = (text) => document.getElementById("demo").innerHTML = text;

  fetch("text.txt").then(getText).then(updateDemo);
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.