There are a couple ways to make AJAX requests. AJAX stands for Asynchronous JavaScript And XML. We use AJAX requests to fetch data from a server after the webpage has already been loaded, which was a game changer for the web.

The flow goes a little something like this…

  • browser creates XMLHttpRequest
  • browser sends HttpRequest to server
  • Server processes HttpRequest
  • Server creates a response and sends the data back to the browser

In JavaScript, we send a XHR request by creating an XMLHttpRequest object.

const request = new XMLHttpRequest();
request.onreadystatechange = () => {
    // readyState = 4: response is ready
    // status = 200: successful
    if (this.readyState === 4 && this.status === 200) {
        // log the response
        console.log(this);
    }
}
request.open("GET", "url");
request.send();

I showed you the XHR request first because I am about to make you really happy when I show you the fetch request. I am a little biased, but it is much easier to understand.

fetch("url").then(response => {
    // log the response
    console.log(response);
});

Whichever way you decide to do it is up to you. Either way, AJAX requests were a game changer for the web, and they are a really important.