A gentle Introduction to Ajax.

Victor Ofoegbu
codeburst
Published in
6 min readOct 31, 2017

--

Imagine you’re deep into your Facebook feeds, you like a post, the page reloads and you had to start all over again.

Not quite painful right, think of how many times you must have reloaded when you like up to 5 posts.

This was the state of the web before the year 2000 when Microsoft introduced the Ajax technology (XMLHttpRequest object) to Internet Explorer which facilitated communication to servers without reloading the page. Soon after other big companies like Google, and Facebook started incorporating it.

Ajax, as you might already know, stands for Asynchronous JavaScript and XML. The word Asynchronous is used to mean pack of events happening at an irregular intervals. You might be thinking what’s with the XML, XML is a format for passing data from server to client, it was dropped in favor of HTML and JSON. Yea, these days, you can pass raw HTML and JSON around the web using Ajax. JSON is a more lighter and straight forward format for passing data around the web.

Basic Ajax request.

To write a basic Ajax request, we need to…

  1. Make an instance of the XMLHttpRequest object.
  2. Open the request.
  3. Send the request.
  4. Handle the request.
var request = new XMLHttpRequest();
request.onreadystate = handleResponse;
request.open('GET', 'url', true);
request.send();
function handleRequest(){
console.log(request.responseText);
}

To explain the code above.

The first line makes an instance of the XMLHttpRequest object.

The second line contains an event (onreadystate), this event fires when the state of the request changes. And the event handler (handleResponse) handles the event and logs the response from the server to the browser console. More on the request state later on.

The third line opens the request. The open() method takes three arguments. The first is the action of the request. It could be GET (to retrieve data), POST (to insert data), UPDATE (to update data) and DELETE (to delete data). The second is the URL to fetch the data from. The third is a boolean value that determines if the request is Asynchronous or not. A True value means an Asynchronous request and False, synchronous (the page will reload), we don’t want that right?.

This is all we need to make an Ajax request. Quite simple right? Now, let’s make a real life example.

Unsplash API

To cement our basic knowledge, we’re going to have an example.

We’ll try to get data Asynchronously from the unsplash.com API, the program will search the API and return images that match our keyword.

Unsplash is a photo collection site. It consists of high quality photos.

So for you to partake, you’ll need to register with Unsplash as a developer, they’ll give you a key so you can have access to the API.

Head to Unsplash now, register as a developer and create a new application. Now you have to understand that unsplash has to take note of the number of API calls you make and take care of security. So you’ll either attach your key to the request url or make a request header. Don’t worry if you don’t understand, an example here…

Let’s break down the code above.

The novel in this case is line 12 right?.

Line 12 sets a request header. Basically, you would want to put your id as a value of the Authorization property. This verifies you were permitted to utilize their API. Without this, most API’s will surely end a 401 error. In case you get that later, just check your client ID is proper.

Some API’s will also allow you attach your client ID to the url of the request like so.

var url = "https://api.unsplash.com/search/photos/?query=home&client-id=your-client-id";

You wouldn’t need a setRequestHeader() method anymore.

You might have also noticed that we have modified the handleRequest function. We introduced two new properties of the XMLHttpRequest object. readyState and status.

readyState stores a number ranging from 0–4 showing the progress of the request.

0 - means request has not been initialized.

1 - means the server connection was established.

2 - means request was sent.

3 - means request is processed.

4 - request was successful and response if ready.

Status property also shows the success of the request.

200 - success.

404 - page not found.

403 - forbidden request.

So, see why we used 4 and 200, to make sure the response was ready before using them.

Copy the above code to your browser console with your unique API ID, hit enter and see what is logged out to the console. Something complex right?.

Returned data from unpslash API.

If you look closely, you’ll not notice it’s a large object comprising of about 2600 objects. Ok, you can’t see that even if you look closely.

Let’s take this further, search in the image above for the urls key, it has full, raw, regular, small and thumb values. We could modify the code above to add the image to the web page asynchronously by pointing our src attribute to the url of the image.

Here’s how this works in a browser.

Getting image of a random home asynchronously.

Sending data to a server

So far, we’ve been dealing with requesting data from a server. What if we needed to save data Asynchronously. Think about form details and other user information. That’s quite simple and not different from the already known format except that we’ll use a POST method this time.

var data = 'name=victor&age=19';function handleRequest(){
if (this.readyState === 4 && this.status === 200){
alert('data was saved');
}
}
var request = new XMLHttpRequest();
request.onreadystatechange = handleRequest;
request.open('POST',server-url,true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data);

In this example, we have some form parameters (data) we would like to send to a server without reloading the page. the data is sent to the server and the message is alerted only when the data was successfully saved.

What then happens when there’s a problem in the server connection?. Well, we’ll treat that in the next phase.

Event and Error handling.

So far, we’ve only talked about instances where the request is successful. A lot of things can go wrong while making async requests. Take this example.

As you can see in the above code, we use the addEventListener method to attach appropriate event listeners to different events that occur when async request is done.

On line 11, we see something new however. The progress.loaded and progress.total. The loaded property holds the current state of the request and total holds the total request state (4). So dividing progress.loaded by progress.total will result in a number less than one when the request is not complete or one when the request is complete and the response returns.

Example.

(3/4) * 100 = 75%. *almost complete*.

(4/4) * 100 = 100%. *complete*.

Using this method, we could give good user experience, offering users retry again messages when requests fail.

Wow!!!.

That’s all for now. This post is aimed at giving an under-the-hood beginner explanation of the XMLHttpRequest object, here’s a post that explains Ajax with jQuery; an easier way to write Asynchronous requests.

I’ll appreciate a clap or two so your friends could see this too. I guess they’ll be cool with it too.

--

--

Product-Focused Software Engineer. Learning to design & build digital experiences