Benjamin Lu

everyday is cool

Updating Part of a Page with JavaScript

A small example can explain the idea behind early Ajax interfaces. Click a button, request a text file, and place the answer into one part of the page. The rest of the page stays where it is.

Give the page a button with ID load and a paragraph with ID result. Put this script after those elements, then save a short message in message.txt beside the HTML.

document.getElementById("load").onclick = function () {
  var request = new XMLHttpRequest();
  request.open("GET", "message.txt", true);
  request.onreadystatechange = function () {
    if (request.readyState === 4) {
      var result = document.getElementById("result");
      result.textContent = request.status === 200
        ? request.responseText
        : "Could not load the message.";
    }
  };
  request.send(null);
};

Serve both files from the same local HTTP server. Click the button, then rename the text file and try again to see the failure state. This recreation uses a modern browser so it can focus on the request and response. Period browsers differed in how they exposed the request object and updated page text.