Introduction to Ajax
Tags: beginners, javascript
Published: 2020-01-06 22:20:51

---
title: Introduction to Ajax
published: true
description: A brief introduction to Asynchronous JavaScript and XML
tags: beginners, javascript
series: FrontEnd Development Zero to Hero
---
> <b>This is an introduction to Ajax and we won't dive deep into the entire subject. In addition the example is quiet basic and can be improved upon.</b>

Some modern applications behave similarly to a desktop application in the sense that when you click or navigate around the application the changes or results occurs almost instantaneously.

A prominent example is [Google maps](https://maps.google.com). When you navigate around the map, new sections are displayed without the need of a browser refresh.

Another example is [DEV](https://dev.to).

In both examples your browser should support and have one technology enabled &rarr; JavaScript.

In technical terms the technology that makes this possible is known as Ajax. On the other side __Ajax is not a single technology but a set of technologies__ that can a make web applications feel more like a traditional desktop app by enabling application to send data from the client to the server asynchronously.

The term Ajax is actually made up of _three words_ namely:

* Asynchronous
* JavaScript
* XML

In computer programming when you execute __something asynchronously, you can perform other task before it finishes__. In technical terms it:

> ... refers to the occurrence of events independent of the main program flow and ways to deal with such events.
&mdash; [Wikipedia](https://en.wikipedia.org/wiki/Asynchrony_(computer_programming))

JavaScript is a technology that was once relegated to the browser but now used on most websites and can run on the server side thanks to tools like NodeJS. We've covered the [history of JavaScript](https://dev.to/ziizium/history-of-javascript-5dlh) in this series.

XML is an acronym for E<b>X</b>tensible <b>M</b>arkup <b>L</b>anguage which is a markup language that defines a set of rules for encoding documents in a format that is both human-readable  and machine-readable ([source](https://en.wikipedia.org/wiki/XML)).

Now, you might think Ajax has to do with performing asynchronous communications using JavaScript and XML, yes, to some extent. But, nowadays, JSON has replaced XML for the most part. JSON stands for [JavaScript Object Notation](https://en.wikipedia.org/wiki/JSON).

Let's take a step back and see where it all started and we'll write some code.

_All screenshots are from <b>Firefox 71.0</b> and its Developer Tools. One particular feature in Firefox 71.0 that's worthy of mention is the <b>multi-line code editor</b> in the console._

<hr>

Ajax is an extremely important technology in web development. The term "Ajax" was coined by Jesse James Garrett in the year 2005 in an article titled [Ajax:  A New Approach to Web Applications](https://web.archive.org/web/20150910072359/http://adaptivepath.org/ideas/ajax-new-approach-web-applications/). 

In the article Jesse James Garret explained the following technologies are incorporated:

* HTML and CSS for presentation
* The Document Object Model for manipulation
* JSON or XML for the interchange of data
* The `XMLHttpRequest` object for asynchronous communication
* JavaScript to bring everything together

We've talked about [HTML](https://dev.to/ziizium/introduction-to-html-3ik4), [CSS](https://dev.to/ziizium/introduction-to-css-1fm), [JavaScript](https://dev.to/ziizium/introduction-to-javascript-ajh) and [Document Object Model](https://dev.to/ziizium/the-document-object-model-3n8o) in this series.

We have not discussed JSON and XML but we can use a _text file_ as the interchange data. Which is what we'll use in this post.

On the other hand, `XMLHttpRequest` is an _object_ for asynchronous communications. The World Wide Web Consortium (W3C) released the first draft specification for the `XMLHttpRequest` object on April 5, 2006.

Presently the [XMLHttpRequest specification](https://xhr.spec.whatwg.org/) is maintained by [WHATWG](https://whatwg.org/) as a __Living Standard__ and at the time this article was published, the standard was last updated on 24<sup>th</sup> September 2019.

The `XMLHttpRequest` abbreviated as __XHR__ is an <abbr title="Application Programming Interface">API</abbr> in the form of an [object](https://dev.to/ziizium/javascript-objects-2m3m). Which means it has methods attached to it. It is implemented in most modern browsers.

Time for some code!.

You'll need three things to follow along. They are:

* A simple HTML file  (i believe you can create this by now)
* A simple text file. Preferably saved with `.txt` extension
* A web server

You can download and install [XAMPP server](https://www.apachefriends.org/index.html) for your operating system. After installation, locate the `htdocs` folder and __create a folder with any desired name__. I'll use `ajax-intro` as shown in the image below.

![A folder created in Windows operating system](https://thepracticaldev.s3.amazonaws.com/i/yfd75znmqkcruo6rm3ky.PNG)

Next, launch the control panel `xampp-control.exe`  (you will find this file in the `xampp` installation directory) and turn on the __Apache__ server by clicking the _Start_ button.

![XAMPP Control panel on Windows Operating system](https://thepracticaldev.s3.amazonaws.com/i/dpm9l6u15h8n08i58xw0.PNG)

Switch over to your browser and navigate to this newly created directory as depicted in the image below.

![An empty folder on a local server](https://thepracticaldev.s3.amazonaws.com/i/rhbr967zmloq3jxemd93.PNG)

Next, create a text file with the `.txt` extension then add some text content (a [lorem ipsum](https://www.lipsum.com/) will do) and save it in this directory.

![Two files in a directory on Windows 10 operating system](https://thepracticaldev.s3.amazonaws.com/i/n5hz9orah4xwspwgx8n5.PNG)

Copy the following HTML snippet below and save it in this directory.

```html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Introduction to Ajax</title>
</head>
<body>
  <div id="mainContent">
    <h1 id="header">Click this title</h1>
  </div>
</body>

<script>
  // we'll add javascript code later
</script>

</html>
```

Load the file in the browser:

![An HTML file opened in Firefox browser](https://thepracticaldev.s3.amazonaws.com/i/ffmnichlixtt2l4a0e8w.PNG)

Switch back to your editor and let's write some script. The subsequent code should be placed between the opening and closing `<script>` tag. 

First, we need to grab the header which is the `h1`. The could would be:

```javascript
// get the header
let getHeader = document.getElementById('header');
```

We would like the user to __click__ on the header for changes to occur on the page, therefore, we'll attach and [event listener](https://dom.spec.whatwg.org/#callbackdef-eventlistener).

Our code will be:

```javascript
/**
  * Attach an event listener to the header. The
  * addEventListener() accepts three parameters.
  * 
  * 1) The name of the event
  * 2) The name of the function
  * 3) useCapture as third parameter (true or false)
  */
  
  getHeader.addEventListener("click", getFile, false);
```

Up next, we need to create the function `getFile()`. The first thing we'll do in the function is to setup an handler. The handler is just a variable that the `XMLHttpRequest` will be attached to.

```javascript
/**
  * The function getFile will contain all the code
  * to make the Ajax request
  */
  function getFile() {

    // set up our request handler
    let myRequest;
  
  
  }
```

What's  next is to create the `XMLHttpRequest` object. This might not be necessary, but, during this process we'll check if `XMLHttpRequest` is present or the `ActiveXObject` in some version of IE.

```javascript
// This code is still inside the getFile() function

/**
  * The XMLHttpRequest is part of the window object
  * that's why we use the dot notation
  */
  if (window.XMLHttpRequest) { // if it's in the window object

       // create the object
       myRequest = new XMLHttpRequest();

  } else if (window.ActiveXObject) { // we are in IE

       // create a new ActiveXObject
       myRequest = new ActiveXObject("Microsoft.XMLHTTP");

  }
```

Now we need to use the `onreadystatechange` property of the `XMLHttpRequest` and we'll attach a function to it. Inside the function we'll check the request state among other things.

```javascript
// This code is still inside the getFile() function

/**
  * We attach a function to the myRequest
  * object via the onreadystatechange method
  */
  myRequest.onreadystatechange = function () {

    // subsequent code should be placed here 

  }
```

The first thing we'll do inside this function is to check if we have a response using the `readyState` property. The `readyState` can return some integer values each representing a different outcome. We also check the `status` value. Both are encapsulated in the `if` statement given in the code snippet below.

```javascript
// This code is inside myRequest.onreadystatechange

/**
  * HTTP Status
  * 200: "Ok"
  * 403: "Forbidden"
  * 404: "Not Found"
  */

/**
  * 0: request not initialized
  * 1: server connection established
  * 2: request received
  * 3: processing request
  * 4: request finish and response is ready
  */

if (myRequest.readyState === 4 && myRequest.status === 200) {

  // code to create paragraph and and the text content
  // will be in this block

}
```

After the response, we create a paragraph text using the `createElement` method which accepts an HTML tag as an argument.

When we get our text file via Ajax request, the `responseText` will contain the content of the text file, the `createTextNode` method is then used to set the text content of this paragraph using the `responseText`. In code:

```javascript
// This code will be inside if (myRequest.readyState === 4 && myRequest.status === 200){}

// create a paragraph tag
let paragraph = document.createElement("p");

// create a text with the response text
let text = document.createTextNode(myRequest.responseText);
```

In the [last post](https://dev.to/ziizium/the-document-object-model-3n8o) i showed how to append an element using the `appendChild` method, we'll do the same here by appending the _text_ we just created to the paragraph.

```javascript
// Still inside if (myRequest.readyState === 4 && myRequest.status === 200){}

// append the text to the paragraph
paragraph.appendChild(text);
```

We also need to append this paragraph to the `<div id="mainContent">`, and it'll appear after the header.

```javascript
// Still inside if (myRequest.readyState === 4 && myRequest.status === 200){}

// get the mainContent
let mainContent = document.getElementById('mainContent');

// append the paragraph
mainContent.appendChild(paragraph);

// We are through with the code for this block
```

We are almost done, all that's left is to open a connection using a `GET` request then we send the file.

The `open()` method is part of the `XMLHttpRequest` that we've saved in the `myRequest` variable. It accepts multiple parameters, here we'll make use of three namely:

* The request type
* The file
* `true` to indicate asynchronous communication

The `send()` method is then used to send the request.


```javascript
/**
  * This code is inside the function getFile itself
  * and not inside the onreadystatechange code nor
  * in the if (myRequest.readyState === 4 && myRequest.status === 200) {}
  */

// Open a connection using GET Request
myRequest.open('GET', 'simple.txt', true);

// send it
myRequest.send();
```

Now we are done. Your entire code snippet should match the following:

```javascript
// get the header
let getHeader = document.getElementById('header');

/**
  * Attach an event listener to the header. The
  * addEventListener() accepts three parameters.
  * 
  * 1) The name of the event
  * 2) The name of the function
  * 3) useCapture as third parameter (true or false)
  */
  getHeader.addEventListener("click", getFile, false);

 /**
   * The fnction getFile will contain all the code
   * to make the Ajax request
   */
   function getFile() {

     // set up our request handler
     let myRequest;

     /**
       * The XMLHttpRequest is part of the window object
       * that's why we use the dot notation
       */
     if (window.XMLHttpRequest) { // if it's in the window object

	    // create the object
	    myRequest = new XMLHttpRequest();

     } else if (window.ActiveXObject) { // we are in IE

	    // create a new ActiveXObject
	    myRequest = new ActiveXObject("Microsoft.XMLHTTP");

     }

    /**
      * We attach a function to the myRequest
      * object via the onreadystatechange method
      */
    myRequest.onreadystatechange = function () {

      /**
        * HTTP Status
        * 200: "Ok"
        * 403: "Forbidden"
        * 404: "Not Found"
        */

      /**
        * 0: request not initialized
        * 1: server connection established
        * 2: request received
        * 3: processing request
        * 4: request finish and response is ready
        */
      if (myRequest.readyState === 4 && myRequest.status === 200) {

	    // create a paragraph tag
	    let paragraph = document.createElement("p");

	    // create a text with the response text
	    let text = document.createTextNode(myRequest.responseText);

	    // append the text to the paragraph
	    paragraph.appendChild(text);

        // get the mainContent
        let mainContent = document.getElementById('mainContent');

	    // append the paragraph
	    mainContent.appendChild(paragraph);

       } // end of if(myRequest.readyState)

   } // end of myRequest.onreadystatechange

   // Open a connection using GET Request
   myRequest.open('GET', 'simple.txt', true);
			
   // send it
   myRequest.send();

} // end of function getFile()
```

Save your file and switch over to your browser and __click the title__, if __you've done everything right, the content of your text file will be added  as a paragraph text every time you click the header__.

![An ajax request performed on Firefox 71](https://thepracticaldev.s3.amazonaws.com/i/sdtrn1qexvw56fjgz6kd.PNG)

In the image above, the _Developer Tools_ is opened and you can observe in the console the details of the request.

You can click the _arrow_ beside the __XHR__ to reveal more details about the request. You can also click the question mark symbol beside the __Response Headers__ to learn more.

![Details of an XHR request shown in Developer Tools on Firefox 71](https://thepracticaldev.s3.amazonaws.com/i/2knl02z3xhhdplcc9xzy.PNG)

You can check the other tabs for more information.

Despite its usefulness for creating for creating dynamic applications Ajax has the following drawbacks among others ([source](https://en.wikipedia.org/wiki/Ajax_(programming)#Drawbacks)):

*  Any user whose browser does not support JavaScript or `XMLHttpRequest`, or has this functionality disabled, will not be able to properly use pages that depend on Ajax
* Similarly, some Web applications that use Ajax are built in a way that cannot be read by screen-reading technologies, such as JAWS.
* Screen readers that are able to use Ajax may still not be able to properly read the dynamically generated content.
* Depending on the nature of the Ajax application, dynamic page updates may disrupt user interactions, particularly if the Internet connection is slow or unreliable

If you would like to dive deeper into this subject, the following resources should be of great help:

* [An introduction to Ajax](http://www.ukoln.ac.uk/qa-focus/documents/briefings/briefing-93/html/)
* [Explaining Ajax](https://adactio.com/articles/1238/)

<hr>

That's it for JavaScript in this series, next we'll give some reference materials and we'll proceed to web design.