AJAX HTTP Requests with Vanilla JavaScript

Advertisement

Advertisement

Introduction

JavaScript in the browser allows you to make asynchronous HTTP requests using AJAX (asynchronous JavaScript and XML). The benefit of making an AJAX call is that it does not require the page to reload, creating an interface that feels smoother and more responsive.

Some frameworks like jQuery make this even easier, but it is important to understand how to do it without a framework.

Let's look at an example of how to do this.

Make AJAX HTTP request

This example shows a full HTML page that you can load up in your browser and test out. It contains a button that you click and a div to output the results of the response. The main component is the XMLHttpRequest object.

A JavaScript function is created to handle the creating and sending of the HTTP request. A second function is created to handle processing the response of the request.

The JavaScript function is called when the button is clicked by binding the onClick event of the button to the JavaScript function.

The results are inserted into an element that is retreived using document.getElementById.

<html>
<body>

  <script>
  function makeHttpRequest() {
    var req = new XMLHttpRequest();
    req.onreadystatechange = processResponse;
    req.open("GET", "https://httpbin.org/get");
    req.send();

    function processResponse() {
      if (req.readyState != 4) return; // State 4 is DONE
      document.getElementById("results").innerText = req.responseText;
    }
  }
  </script>

  <button onClick="makeHttpRequest()">Make request</button>

  <h2>Results</h2>
  <div>
    <pre id="results"></pre>
  </div>

</body>
</html>

Conclusion

After reading this you should understand how to make a simple AJAX HTTP request and display the results in the HTML.

References

Advertisement

Advertisement