Image Courtesy: xresch@pixabay

The Epic of Async — Part 1 : A tale of AJAX

Rahul Shenoy
9 min readOct 6, 2018

--

This is the first of 3 part series which explains Asynchronous JavaScript in some detail with approaches and frameworks to work with async. This section is about the early days of Asynchronous scripting, covering how AJAX came to be and it’s raise to fame with a little coverage of those programming days.

Hi folks, AJAX has been around for a very long time and all of us are very well aware of it. Asynchronous JavaScript And XML - simple, right? We call them with JavaScript, passing around JSON asynchronously. But, there is something not right here, oh, where is XML?

A hero is born

So when was AJAX created and by whom? Dennis Ritchie & Bell Labs? no no, they came up with C, the undisputed king of all. Tim Berners Lee? wrong again. Now, don’t be surprised if I say Microsoft… yes, it was in fact, Microsoft. This was a time when browsers would receive data only on reload. Entire HTML page had to be retrieved and loaded again for every small change. So if you create a post on Facebook, page would refresh and load the post. Nobody would see it until they refresh the page, and nobody would even like your post since it would take another long reload for them when they hit like, which apparently, nobody likes.

In the early-to-mid 1990s, most Web sites were based on complete HTML pages. Each user action required that a complete new page be loaded from the server. This process was inefficient, as reflected by the user experience: all page content disappeared, then the new page appeared. Each time the browser reloaded a page because of a partial change, all of the content had to be re-sent, even though only some of the information had changed. This placed additional load on the server and made bandwidth a limiting factor on performance.

In 1996, the iframe tag was introduced by Internet Explorer; like the object element, it can load or fetch content asynchronously. In 1998, the Microsoft Outlook Web App team developed the concept behind the XMLHttpRequest scripting object. It appeared as XMLHTTP in the second version of the MSXML library, which shipped with Internet Explorer 5.0 in March 1999.

-Wikipedia

MSXML is an interesting library, let’s talk about it in another article and not deviate too much here. So, that’s how a hero, AJAX was born, who like IE, was going to rule the world of web for a long time to come.

Calling AJAX

It should be simple, call him by name, right? Not quite, it did not happen until jQuery emerged, who pushed AJAX to newer heights eventually. This is how AJAX requests are made in JavaScript -

var xhr = new XMLHttpRequest();
xhr.open('GET', 'server-api-url');
xhr.send(null);

Notice the XMLHttpRequest class being used to create an instance of AJAX object. The AJAX object then opens a connection, specifying a method (GET in the example) and endpoint (denoted as server-api-url), and later the request is triggered with send function of the object, that’s it, we have an AJAX request there. But we haven’t received the response yet, let’s see how it’s done -

xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// Success
}
else {
// Failed
}
}
};

Here comes the most important part, onreadystatechange, which is an event handler to help AJAX decide if the response has arrived. What we are doing here is, first, verify if the request has been executed and response has arrived. There are 5 ready states (0 - not initialized, 1- connected, 2 - received, 3 - processing, 4 - completed) which an AJAX request goes through. The onreadystatechange event fires every time the state changes to next in the order. What we are interested is when the request is completed, hence, we are processing only ready state 4 in the above example.

Once complete, then we check the status code returned, 200 means a success, everything else is a problem. When the response arrives, it loads a couple of xhr attributes, most important of them being responseText, responseXML, which contain the response values in text and XML form.

if (xhr.status === 200) {
console.log(xhr.responseText)
}

But did we just use the XMLHttpRequest to create AJAX request? The truth is, that is not how the first AJAX calls were made, remember XMLHttp was a function of MSXML library? the original instrument to make AJAX calls. Let’s have a glance at the interesting technologies Microsoft pioneered at some point, but were forgotten as time went by.

Microsoft’s ActiveX

ActiveX is a software framework created by Microsoft that adapts its earlier Component Object Model (COM) and Object Linking and Embedding (OLE) technologies for content downloaded from a network, particularly from the World Wide Web. Microsoft introduced ActiveX in 1996. In principle, ActiveX is not dependent on Microsoft Windows operating systems, but in practice, most ActiveX controls only run on Windows. Most also require the client to be running on an x86-based computer because ActiveX controls contain compiled code.

ActiveX is still supported as of Windows 10 through Internet Explorer 11, while ActiveX is not supported in their default web browser Microsoft Edge (which has a different, incompatible extension system).

-Wikipedia

ActiveX had one primary objective in mind, to be able to connect different applications through an Object Model. The Object model, like DOM of HTML, was being created for all key applications and was made accessible through application SDKs and APIs. Coolest thing, right? This means you could create a word document from JavaScript using ActiveX, where ActiveX binding between applications (IE and MS Word) takes care of communication when the API is called. To try it, paste the code below in console and run it, however, this works only on IE if you have enabled ActiveX from internet settings. Alternatively, you can browse to a trusted site and run the code opening the console there.

var Application = new ActiveXObject ("Word.Application");
var instance = Application.Documents.Add();
Application.Selection.TypeText("ActiveX Works here!")
Application.Visible = true;

Just to illustrate the concept a little more, the following code fills in a multiplication table in Excel -

var Application = new ActiveXObject ("Excel.Application");
var instance = Application.Workbooks.Add ();
var sheet = instance.Worksheets.Add();
sheet.Name = "Times table";
Application.Visible = true;
var r = 0, c = 1;
var interval = setInterval(function(){
sheet.Rows(++r+1).Columns(c).Value = " "+c+" X "+r+" = "+(c*r)+" ";
if(r==10){
r = 0;
sheet.Rows(1).Columns(c).Value = " Table " + c;
c ++;
if(c>10) clearInterval(interval);
}
}, 100)

MSXML was one such library created solely to work with XML. It included methods to access and manipulate XML Document Object Model, Schema Object Model etc. One of those methods was XMLHttp, so the original AJAX instantiation looked like this -

var xhr = new ActiveXObject('Microsoft.XMLHttp');

Hello World!

Although not a W3C standard, Other browsers started working on creating a similar mechanism for asynchronous requests since this was a super cool feature to have. Mozilla was next to reinvent the wheel (they knew how the wheel looked like, so technically they just built it again) with XMLHttpRequest, followed by Safari and Opera. Soon W3C came up with XMLHttpRequest standards in 2006, and again in 2008, then fell back to 2006 in 2011 (yeah, they really did that).

By 2006, everybody was in the game but due to lack of W3C standards every vendor ended up with their own standard. Standards which were different for everyone, well, they just created an oxymora there and this was not even a grammar class. So, that’s what hit most people who wanted to use the newfound superpower, paired with the complexity of using it. All the world needed now was a simple wrapper (not the superman, but he returned too) to handle the complexity and cross-browser compatibility of AJAX.

Let me hold there, first, let’s sum all our learning up here and write our hello world program with AJAX -

var xhr = null;
if (window.XMLHttpRequest) {
// If IE7, Mozilla, Safari, and so on: Use native object.
xhr = new XMLHttpRequest();
}
else
{
if (window.ActiveXObject) {
// ...otherwise, use the ActiveX control for IE5.x and IE6.
xhr = new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log("Hello world")
}
else {
console.log("Hello world with error!")
}
}
};

That Hello world program sounds more like a Hell-o world to me. There should be a better way to do that, right?

$.ajax

2005–06 was an important milestone which marked a number of mainstream JavaScript libraries which popularized JavaScript beyond it’s typical use case of client validations and alerts. Libraries like YUI, Dojo and most importantly jQuery were introduced to the world in this time frame, which revolutionized the way JavaScript was being used and perceived.

jQuery, which is the most widely used and deployed library of all time, is highly relevant even today. jQuery drew inspiration from cssQuery, which was based on a simple idea, enabling developers to use CSS element selection rules in JavaScript. This allowed users to be able to select DOM elements for processing a lot more conveniently than the original - selection by Id or tag name. jQuery took this idea and on top of that, created a lot more functions to perform extended selection, DOM manipulation and chaining.

One of those functions was $.ajax, which simplified AJAX calls and eliminated the pain of handling cross-browser standards. Let me demonstrate this with a hello world program using jQuery -

var ajaxConfig = {
type: 'GET',
url: 'server-api-url',
dataType: "JSON",
success: function (data) {console.log('Hello world');},
error: function() {console.log('Hello world with error!');}
}
$.ajax(ajaxConfig);

That’s very clean, just define everything in a configuration and pass it to $.ajax. There is no event handling, no need to manually verify HTTP status codes or ready states. Emphasis is only on what is needed, the URL, type of request and data, and handlers for success and error.

jQuery simplified ajax even more with custom functions like get and post, see the example below -

function success(data) {console.log('Hello world');}
function error(data) {console.log('Hello world with error!');}
$.get('server-api-url').done(success).fail(error);

Way cleaner, right?

.. and the others

AJAX was named after a mythical hero of same name from Greek mythology. The name made perfect sense, first of all AJAX was (is) a hero, and name represented the constructs on which it was built, Asynchronous JavaScript where data was in the XML format (Now we know why it was not called Achilles or even Brad Pitt).

XML was and is being used by Microsoft as a generic data format (and rightly so), and due to it’s technology agnostic plain text format it was the best fit for passing data around (remember SOAP?). The immediate benefits of AJAX were -

  1. It avoided page load when whole page was not required to be refreshed
  2. It created a technology-agnostic way to transmit data
  3. It minimized the volume data that needs to be carried over the network
  4. It let the client (browser) take care of processing whole presentation layer, reducing a huge burden on servers.

These were groundbreaking, and defining elements of today’s web technology. They allowed super rich pages to load once and do partial refresh (now your like on Facebook just sends few bytes of data and receives few bytes instead of few hundred posts on every hit).

However, there were other concepts too, in the first web service I built (an asynchronous grid with add, edit and delete options), the service returned processed HTML instead of XML. Which was easy since the server languages were strongly equipped to easily process templates and fill in the blanks with data. I would replace only the part of page which needed refresh (say add would add a new row to HTML table, edit would replace the row and delete would delete the row — no HTML was returned there). I soon found out that, it wasn’t a new concept but there already exists something called AJAH, asynchronous JavaScript and HTML.

Now coming to AJAX, the XML part, was not really necessary. When Microsoft introduced AJAX in MSXML, with the class XmlHttp, it wasn’t really a binding constraint to use XML. HTML being XML (without a DOCTYPE? hmm…), was not really an outlaw. But then, most people use JSON? Why JSON?

  1. JSON is native to JavaScript, the language of browsers. Which means, you do not need google translate when you got the email in plain English!
  2. JSON consumes lesser space to transmit the same amount of data compared to XML as it avoids opening and closing tags, repeating tags for arrays etc.

Then why are we not calling it AJAJ? Well, actually, there is no specific reason for that, why move away from the iconic Greek hero without a reason. The concept was originated with XML tagged along, and it’s already well-known with this name, doesn’t make sense to call it AJAF and AJAP for flatbufs and protobufs. Brigitte Jellinek in this blog tells us that X does not denote XML anymore, it’s ‘X’, which could be anything, makes sense right?

Moreover, what’s in a name.

“A rose by any other name would smell as sweet”

— William Shakespeare

--

--

Rahul Shenoy

Senior Architect - Web Technologies, Microservices and DevOps