AJAX Mechanism

Chapter 2 7 mins

Learning outcomes:

  1. Normal vs AJAX request-dispatch mechanism
  2. The XMLHttpRequest() constructor
  3. The open() and send() methods

How AJAX operates?

As we saw in the previous AJAX Introduction chapter, AJAX isn't a language, but rather a mixture of different languages and APIs to aid in the task of asynchronously communicating with servers. So how does AJAX work at the most basic level? Here's how..

First let's see how does a normal HTTP request work:

  1. You make a request for a webpage, by entering its URL in the browser address bar.
  2. The request is resolved and sent to its respected server.
  3. The server processes the request and, after processing it, sends back a response to it.
  4. The browser receives this response, parses it, and shows it to you.

This is a simple step-by-step explanation of how a normal HTTP request works. Now, in contrast and comparison to this let's see how an AJAX request works:

  1. Once again a request is made by the browser to a given server, but this time it is made explicitly by the developer in code.
  2. The request is resolved and sent to its respected server.
  3. The server processes the request and, after processing it, sends back a response to it.
  4. The browser receives this response and instead of showing it to you right away saves it in a property.
  5. Finally using events and the HTML DOM API, the developer gets this response to be shown in the browser, or do other things based on it.

This is a simple AJAX request. Notice the differences between a normal request and the one sent using AJAX.

In AJAX the developer writes code himself to make a request and deal with the response. In contrast to this, in a normal request, both these aspects are essentially dealt by the browser itself - the developer doesn't has to write any request-initiating or response-handling codes.

Thus it turns out that:

In AJAX, everything is the same as in a normal request except for generating the request explicitly and then also dealing with it manually, taking into account all possible errors and problems.

So in a nutshell, with control in our hands, in AJAX, we can update any part of the actual webpage using a handful of dynamic DOM manipulation techniques without needing to reload anything - everything happens in the background. This is AJAX - do refreshes without reloads!

This workflow might seem simple or rather trivial at this stage, but at the scale of a large and complex web application, like Google Maps, it really is a jaw-dropping improvement in the possibility diagram of the web. Believe it!

Anyways, it's now time to elaborate on all the steps in the mechanism of AJAX described above in a bit more detail and see where the 'heart of AJAX' - the XMLHttpRequest() object lies.

The XMLHttpRequest() constructor

To implement AJAX in an application you have to use the function, or better to say - the constructor - XMLHttpRequest().

It creates an instance of an object which can be used to make an asynchronous request to the server and then deal with the whole process following that - events, listening to state change events, handling errors, showing responses and much more.

In effect, this is the start of the first step in the mechanism of AJAX shown above. Let's recap the step once again.

Once again a request is made by the browser to a given server, but this time it is made explicitly by the developer in code

So before anything let's first create an instance of the XMLHttpRequest() object.

var xhr = new XMLHttpRequest();

Then after this, we'll need to tell which page we want to request for, using the open() method on the instantiated object xhr above.

The open() method

Intuitively you think of this method as initialising your request (but not actually sending it). More intuitively you can even think of it as opening up the doors from where you'll be sending your AJAX request - obviously you can't send something just past the door; you have to open it!

The first argument to open() is the HTTP method you wish to send the request in. Common values are "GET" and "POST".

You'll learn more about HTTP request methods in the chapter AJAX Request Methods.

The second argument is the location of the file you wish to request for, and is also given as a string. Lastly comes a boolean argument telling whether the request shall be asynchronous or not; by default this is set to true meaning that the request is asynchronous.

Shown below is a straightforward example of calling the open() method:

var xhr = new XMLHttpRequest();
xhr.open("GET", "ajax.txt", true);
By default the third argument to open() is true - and you won't find it any useful to set it to false - otherwise you'll be going away from the essence of AJAX and its first 'A' i.e Asynchronous!

The send() method

Finally we need to send the request using the send() method. This is where all the interest begins - we've now actually dispatched the request, past the doors we opened previously, to the server and waiting for a response.

var xhr = new XMLHttpRequest();
xhr.open("GET", "ajax.txt", true);

This completes the first step in the mechanism of AJAX - now over to the second.

Server processing

The second step of processing the request happens entirely at the server-end.

It parses the request made by the client, finds the requested page, executes it and consequently returns a response. The response consists of the status code which can indicate what happened back at the server - whether the request was successfully completed or whether some error occured. We'll discover more to responses as this course proceeds.

Sometimes, in fact, majority of the times, the request is sent along with some data which the server can process in addition and return different results based on it.

For instance an webpage might have a selection list with multiple options, let's say, to inspect the annual fee of different universities. With the onchange event the select element can dispatch different AJAX requests along with different GET parameters and receive different responses for each of them.

We'll learn all these tiny aspects of AJAX soon in this course.

Dealing with the response

In the third step, the response sent by the server to the browser is captured inside the responseText property as plain text, and in some cases, also in the responseXML property as a traversable DOM tree. We'll discuss both these response-handling properties in fine detail in the AJAX Response Handling chapter.

Lastly in the fourth step this response can be used together with DOM methods and properties like innerHTML to update the whole web page or just parts of it all seemlessly and dynamically, as a result completing the AJAX fetch.

Moving on..

Note the fact that even in this section certain things are kept simple and fundamental such as the third and fourth steps to reduce clutter being thrown at you all at once.

We want you to follow along and understand necessary functionalities required by a complete AJAX fetch, rather than just memorising a piece of code and never understanding the purpose of each function to the core.

In the next chapter we will dig even deeper into the XMLHttpRequest() object and see how some state-defining properties and events can be used to handle responses sent by the server, at the right instance of time.