JavaScript XMLHttpRequest — Basics

Making HTTP requests with XMLHttpRequest is simpler than you think — code and diagrams included

Peter Sz
The Startup
4 min readMay 28, 2020

--

This article describes what XMLHttpRequest is, how to use it, and shows a basic use case.

The scope of this article is the absolute minimum that you need to understand XMLHttpRequest and to get it working. We will use XMLHttpRequest to retrieve data from restcountries.eu. The data we will get from the website is a list of all countries in the world with details like their currencies or capitals.

I couldn’t start without this statement — XMLHttpRequest is an object. It allows you to retrieve data from a server and update your Web page. It’s got a whole bunch of methods and properties so if you leave shallow waters too early, it may seem a bit more difficult than it really is.

In its simplest form, an HTTP request can be made using these steps

  • create an instance of XMLHttpRequest object,
  • open a URL,
  • send the request,
  • handle the response — event handler.

XMLHttpRequest Object

Figure 1. Newly created XMLHttpRequest Object

In the example code, I print XMLHttpRequest object in the console so that you can see its bones and guts. As you can see in the screenshot above (Figure 1), there are many properties, methods, and events that can be very useful when it comes to making an HTTP request.

There is much more than you can see in the picture — I didn’t click that little arrow next to __proto__: XMLHttpRequest at the very bottom. I dare you to do that if you decided to try my example code on your machine.

“Fear not, for I will make it simple” — me

The bare minimum that you need to make a request is:

  • open() method
  • send() method
  • onload property (or an event listener). Set it to a callback function to be executed after the request completed successfully.
  • status property containing the status of the response (optional)

The first two are hiding in the scary depths of __proto__: XMLHttpRequest.

XMLHttpRequest

Here is the example code. Have a quick look and see how simple it can be. Also available here: https://gist.github.com/VYV7/8914228a7a77ab3926df914a93503bb5

Line 5 creates a new instance of XMLHttpRequest object and then we immediately print that new object using consol.log(). See Figure 1 for the output. At this stage, the object is not initiated.

Line 10 defines and sets the callback function to be called when the request completes successfully.

Line 26 initializes the request by defining the HTTP request method — GET, and the URL. GET gets you requested data from the server. Another possible method could be POST which sends data to the server.

Line 30 sends the request. By default the request is asynchronous, meaning send() method returns as soon as the request is sent. It is important to note that we continue executing the code following the send() method while the request is on a grand journey to the server. <Indiana Jones theme>

XMLHttpRequest — asynchronous

Response

When the request completes successfully, onload callback function fires.

Here inside the callback function (line 13), we check the request status and either handle the received data or print the error message. The error case can be tested by adding an extra character at the end of the URL (line 26).

There are 5 categories of HTTP request statuses:

  • 100–199: informational responses,
  • 200–299: successful responses,
  • 300–399: redirects,
  • 400–499: client errors,
  • 500–599: server errors

The most famous one, I think, is 404 — Not Found. 404 basically means that the server can’t find the requested resource.

If the request status is 200 (OK: the data has been fetched),

  1. we print data in its raw text form (JSON string, see Figure 2) — line 15,
  2. then convert it into a JavaScript object (array of objects) — line 16,
  3. we print that array of objects (see Figure 3) — line18

Now, we can play with data from the server.

Figure 2. Raw Response (JSON string)
Figure 3. Converted Response (array of objects)

Summary

The XMLHttpRequest object is very handy. If we removed the comments and DEBUG lines, we would end up with just a few lines of code. Although the XMLHttpRequest object has many methods and properties, we can make simple requests using just 3 or 4 of them.

Obviously, there is always more than one way of doing things. For example, instead of using JSON.parse() to convert a JSON string to a JavaScript object (line 16), we could make use of the responseType property.

myRequest.responseType = ‘json’

This specifies the data type sent from the server. The default value of this property is text — that’s why we had to parse it. If we set it to ‘json’, then the array of objects (countries) will be available directly in myRequest.response property.

We can do a lot with XMLHttpRequest object and the best way to learn it is to play with it in isolation from any more complex code.

--

--

Peter Sz
The Startup

Software engineer and nature enthusiast living in Scotland.