#4 Our First AJAX Call XMLHttpRequest

Here is the link to 3rd article of this series: Asynchronous Javascript, AJAX and APIs in Node.js

Ruckaiya Mira
7 min readJul 5, 2022
AJAX Sends an XMLHttpRequest To a Server

Don’t get intimidated by seeing this code!

I’ll explain each and every line of code from beginning to end.

So now that we know about AJAX and APIs, let’s actually make our first API call.

In today’s story, we’re going to build a small application to demonstrate how to code to make AJAX and API calls.

Our application will contain data about a certain country, and this data about the countries are actually gonna come from a third party online API — (just as we learned it in the last lesson). I think it feels really magical, and next level, to be able to do this.

The API that I selected for this project is — https://restcountries.com/

And so let’s now start working on this.

Now in JavaScript, there are actually multiple ways of doing AJAX calls. But we’re gonna start with the most old school one. And that’s called the XMLHttpRequest function.

Now again, as I mentioned, this is the old school way of doing AJAX in JavaScript. But I’m still showing it to you for two reasons.

  • First, I want you to know that XMLHttpRequest exists because you might actually need it in the future.
  • And second, I want to show you how AJAX calls used to be handled with events and callback functions. And so only after that, we should move on to a more modern way of handling asynchronous JavaScript, which is gonna be a feature called Promises.

Steps to send an HTTP request

There are three steps for a client from sending an HTTP request to receiving an HTTP response:

  • The client writes the HTTP request message and sends it to the server.
  • The server accepts the HTTP message, processes it, and then returns the HTTP response message to the client.
  • The client receives the HTTP response message, parses the message, and retrieves the data.

The HTTP request message contains:

  • HTTP Methods. Include GET , POST , PATCH
  • URL
  • Header
  • Body

The HTTP response message contains:

  • Status Code
  • Header
  • Body

We’ll learn more about Status Code, Header and Body later in the node.js series. For now just know what HTTP request and response contains.

In our JavaScript code, all we need to do is:

  • Set Method, URL, Header, and Body for the request message during the sending HTTP message stage.
  • In receiving an HTTP response, read information such as Status Code, Header, Body, and so on from the response message and process logically.
First 2 steps to send an HTTP request

In the example above, we made a GET request to restcountries API to get basic information about a specific country.

  1. XMLHttpRequest is a constructor that generates an instance object for sending an HTTP request and receiving an HTTP response. Let’s call this instance object request.
  2. The request.open method is used to set the Method and URL of the HTTP request message. It takes two arguments, the first being the HTTP Method and the second being the destination URL.
  3. Finally, we send the HTTP request through the request.send method. (This method can take a single parameter to set the Body of the HTTP message. When we call this method, the browser will actually start sending the HTTP request….. more on HTTP Body later).

Why we don’t assign variable to the result?

Now, in order to get the result, we can’t do something like this.

Don’t set send request into a variable;

And the reason why we cannot set some variable to this result here is because the result is simply not there yet. This AJAX call that we just sent off here, is being done in the background, while the rest of the code keeps running. And so this is the asynchronous, non-blocking behavior that we talked about in the last lesson. Instead, what we need to do is to register a callback on the request object for the load event.

So request, and then again, our old friend, .addEventListener. And here on the request, we will wait for the load event. Here, we basically again send off the request. And that request then fetches the data in the background. And then once that is done, it will emit the load event. Hence, using this event listener, we are waiting for that event. And so as soon as the data arrives, this callback function here will be called.

Then we logged the result to the console.

The original data comes as a big string of text in an array containing an object. So we console logged to check the type of data we got.
The response i.e. the data that we got is JSON

Now, we need to convert this to an actual JavaScript object.

Because what we have here right now is JSON. Remember that JSON is basically just a big string of text. And so what we need to do here is to then convert that. We do that by JSON.parse(this.responseText).

Let’s take a look at the data. You’ll see that this is actually an array containing one object.

I called getCountryData function thrice down in my code, that’s why you’re seeing 6 logs from 2 console logs for each country.

Let’s destructure that to get the object — const [data] = JSON.parse(this.responseText);

The this keyword inside of this function is the request. (So we could also do request. but let’s just use the this keyword). And this response is in the property responseText . Again, this property here is of course, only gonna be set once the data has actually arrived. If we tried to set it out after request.send(), then that wouldn’t work. We can still try that just to see request.responsetext.

But from the second log function, we have our first data. That’s great, and as you see, this is the result of our very first AJAX call. You can see that this kind of looks like a bunch of data about Bangladesh indeed.

Printing response into DOM

The rest of the code attached above should be self explanatory.

I’ve created a template literal to print the data from our API call in a table form.

To explain what Object.values() is doing here….. Object.values() method is returning an array containing all the object’s own property values. If you analyze the received data object carefully, you’ll see arrays and nested objects in some of the properties of this mega data object!! Object.value() method helps in getting the values of the keys in objects.

Calling getCountryData function

By calling these functions here thrice, we will basically have three AJAX calls happening at the same time. In parallel, so to say.

And if we reload this page a couple of times, you’ll see that they appear in a different order each time. That’s because the data arrives at a slightly different time, each time we’re loading the page. In fact, this really shows the non-blocking behavior in action.

As we call getCountryData here with Bangladesh, for the very first time, it sends off this request, and then JavaScript moves on in the code right away. And so it goes right to this next line. And this, of course, fires off another AJAX call immediately, way before the data of Bangladesh has actually arrived. We will have 3 AJAX calls happening at the same time. And so whichever one arrives first, will then fire the load event first.

If the first one is to AJAX call for Canada, well, then the first element that’s going to be printed in the DOM will, of course, be the one from Canada.

And only after that the data for Bangladesh arrive. And then the callback function is called with the data of Bangladesh. And the same would be true no matter how many other requests we would fire off here.

Showing what happens after page reloads

Now, if we actually wanted these requests to be made in a specific, predefined order, then we would basically have to chain the requests. This means making the second request only after the first request has finished. And that’s actually what we’re gonna do in the next lesson so that I can show you something that we developers call callback hell.

FINAL CODE:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Asynchronous JavaScript ~ AJAX</title>
</head>
<body>
<script defer src="ajax.js"></script>
</body>
</html>

ajax.js

const getCountryData = function (country) {
const request = new XMLHttpRequest();

request.open('GET',`https://restcountries.com/v3.1/name/${country}`);
request.send();
// console.log(request.responseText);
request.addEventListener('load', function () {
// console.log(this.responseText);
// console.log(JSON.parse(this.responseText));
const [data] = JSON.parse(this.responseText);
// console.log(data);
const lang = Object.values(data.languages).join(',');
const currencies = Object.values(data.currencies).map((currency) => currency.name).join(',');
const borders = Object.values(data.borders).map(border => border).join(',' + ' ');

const html = `

<table>
<tr>
<td>Country Flag:</td>
<td><img src="${data.flags.png}"/></td>
</tr>
<tr>
<td>Country Name:</td>
<td>${data.name.common}</td>
</tr>
<tr>
<td>Region:</td>
<td>${data.region}</td>
</tr>
<tr>
<td>Continent:</td>
<td>${data.continents}</td>
</tr>
<tr>
<td>Borders:</td>
<td>${borders}</td>
</tr>
<tr>
<td>Population:</td>
<td>${data.population} ~ ${+(data.population / 1000000).toFixed(1)} M</td>
</tr>
<tr>
<td>Language: </td>
<td> ${lang} </td>
</tr>
<tr>
<td>Currency: </td>
<td> ${currencies} </td>
</tr>
</table>
<br/>
`;
const divEl = document.createElement('div');
divEl.innerHTML = html;

document.body.appendChild(divEl);
console.log(html);
});
};
getCountryData('bangladesh');
getCountryData('canada');
getCountryData('saudi');

If you like to read my articles … ♥️ follow me & subscribe to my email list on medium: https://medium.com/@ruckaiya.awf5 to be notified of the publication of the next article.

--

--

Ruckaiya Mira

Daughter | Sister | Software Engineer | Managing Director @worldschoolofbangladesh | Learn programming like never before.