Javascript — XMLHttpRequest

nathan
4 min readJul 24, 2019

--

Photo by NASA on Unsplash

XMLHttpRequest is a browser built-in object. The object that we can use to make a request to the web-server. Javascript can help us to interact with the object. There’s a process before we get responses data from the web-server. We can do some logic after or before we get data from the web-server. This article is going to show you how to make a simple request to a web-server with Javascript XMLHttpRequest object.

Let’s prepare your favorite text editor or even online text editor that can use Javascript like CodeSandbox, Codepen, etc.

var request = new XMLHttpRequest();

HTML

First of all, we make a simple container div to show the world what we got from web-server. I have created an Html file called index.html. In there, we create a single div to be the container of our data.

<!DOCTYPE html>
<html>
<head>
<title>XMLHttpRequest</title>
</head>
<body>
<div id="root">
</div>
<script src="src/custom.js"></script>
</body>
</html>

As you can see, there is a div element with root as its id, so we can reference the element from it through Javascript. There’s also a script tag to importing external Javascript file into the Html called custom.js. You don’t need to follow by importing external Javascript file source but you can also write Javascript syntax in the script tag without importing any external Javascript file source.

<!DOCTYPE html>
<html>
<head>
<title>XMLHttpRequest</title>
</head>
<body>
<div id="root">
</div>
<script>
// your script goes here...
</script>
</body>
</html>

Javascript

Next move is going to the Javascript. As you can see before, we are including Javascript into the Html file. After that, we can do some logic with Javascript that can take effect on the Html. Then, we can start making an XMLHttpRequest object with Javascript.

var request = new XMLHttpRequest();

Now we have an object called request. We can make a request to the web-server with it. So, let’s make it happen.

request.open(METHOD, URL, [ASYNCHRONOUS], [USER], [PASSWORD]);

The open object method having parameters that accept method, URL, and asynchronous state, user, and password. The method means request method, is it a GET or POST. URL means the file location in web-server that return responses. ASYNCHRONOUS is an option state, we can give it true or false. Need to remember, XMLHttpRequest is an ASYNCHRONOUS process, so it can allow you to access the page while we are requesting data from the web-server. If you are giving the state to false, so the process becomes SYNCHRONOUS, but by default, it will become true. USER and PASSWORD parameter are given if the location of the file on the web-server needs it. For example, if you want to go to the profile detail page, the web-server needs your username and password, if valid, the web-server can give your profile details. But you don’t always to put your username and password if the file doesn’t need it.

For this example, I’m going to use fake REST API from JSONPlaceholder. I’m going to use one of the file locations which is /users. The file location returns 10 users in an array of objects, doesn’t need a username or password, and its method is GET. Let’s see how to do it.

var request = new XMLHttpRequest();
request.open("GET", "https://jsonplaceholder.typicode.com/users");
request.send();

Now, we want to GET response from the web-server with the specified file location. After that, we can get the response of the web-server with another XMLHttpRequest object method. But there are two ways to retrieve responses from the web-server. Here it is.

// 1st
request.onload = function() {
document.getElementById("root").innerHTML = request.response;
}
// 2nd
request.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
document.getElementById("root").innerHTML = request.response;
}
}

The first one is using onload event from XMLHttpRequestEventTarget. Let me quotes the definition from the Developer Mozilla sites.

XMLHttpRequestEventTarget is the interface that describes the event handlers you can implement in an object that will handle events for an XMLHttpRequest.

This means we can use the event listener from our request object since it is the XMLHttpRequest object that will handle events because there is XMLHttpRequestEventTarget interface to the event target. For more event properties, you can go to Developer Mozilla XMLHttpRequestEventTarget.

The second way is using XMLHttpRequest object properties called onreadystatechange as a function. It will be called when the readyState property change. Take a look at w3school sites what readyState and status is.

readyState: Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

Status : Returns the status-number of a request
200: “OK”
403: “Forbidden”
404: “Not Found”
For a complete list go to the Http Messages Reference

So you may know why we need to comparing readyState with number 4 and status with number 200. The reason is, so we know the response from the web-server is ready and we can get the result by using the response properties. But the response of the web-server is still the same.

So, you now know how to get data from the web-server, even if it’s fake REST API. Hopefully, you can try another web-server with another file location with this article. Actually, the snippet here is not the best yet. It still needs some adjustment to fulfill your needs.

Thanks for your time.

--

--