loading...

Introduction to Ajax

ziizium profile image Habdul Hazeez ・9 min read

FrontEnd Development Zero to Hero (67 Part Series)

1) FrontEnd Development: Zero to Hero 2) What is the Internet 3 ... 65 3) What is the Web 4) Web Browsers 5) Tools for Web Development 6) Introduction to HTML 7) History of HTML 8) The HTML specification 9) HTML Elements and Tags 10) Replaced Element and Void Element 11) Writing Accessible HTML 12) Validating HTML documents 13) HTML Resources and Reference 14) Introduction to CSS 15) History of CSS 16) The CSS Specification 17) CSS Properties 18) CSS Selectors 19) CSS Units 20) CSS Specificity 21) The CSS Cascade 22) CSS Inheritance 23) The CSS Box model 24) CSS Margin Collapse 25) CSS Positioning 26) CSS z-index 27) CSS colors 28) CSS Backgrounds 29) CSS Variables 30) CSS Floats 31) CSS Block Formatting Context 32) CSS Flexbox part 1 33) CSS Flexbox part 2 34) CSS Grid part 1 35) CSS Grid part 2 36) CSS Media Queries 37) CSS Typography 38) CSS Animations and Transitions 39) CSS Naming conventions 40) Writing maintainable CSS 41) CSS References and Resource 42) Introduction to JavaScript 43) History of JavaScript 44) The EcmaScript specification 45) Introduction to programming 46) JavaScript Variables 47) JavaScript Arrays 48) JavaScript Objects 49) JavaScript Numbers 50) JavaScript Conditionals 51) JavaScript Loops 52) JavaScript Functions 53) The Document Object Model 54) Introduction to Ajax 55) JavaScript References and Resource 56) Introduction to Web Design 57) History of web design 58) Site Layouts in CSS 59) Introduction to Responsive web design 60) Introduction to Progressive Enhancement 61) Introduction to User Interface design 62) Introduction to user experience design 63) Introduction to Web accessibility and usability 64) Introduction to Color theory 65) Web design References and resource 66) Series final project 67) Building your career as a developer

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.

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. When you navigate around the map, new sections are displayed without the need of a browser refresh.

Another example is DEV.

In both examples your browser should support and have one technology enabled β†’ 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.
β€” Wikipedia

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 in this series.

XML is an acronym for EXtensible Markup Language 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).

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.

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

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


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.

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, CSS, JavaScript and Document Object Model 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 is maintained by WHATWG as a Living Standard and at the time this article was published, the standard was last updated on 24th September 2019.

The XMLHttpRequest abbreviated as XHR is an API in the form of an object. 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 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

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

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

Next, create a text file with the .txt extension then add some text content (a lorem ipsum will do) and save it in this directory.

Two files in a directory on Windows 10 operating system

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

<!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

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:

// 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.

Our code will be:

/**
  * 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.

/**
  * 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.

// 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.

// 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.

// 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:

// 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 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.

// 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.

// 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.

/**
  * 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:

// 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

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

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):

  • 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:


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

FrontEnd Development Zero to Hero (67 Part Series)

1) FrontEnd Development: Zero to Hero 2) What is the Internet 3 ... 65 3) What is the Web 4) Web Browsers 5) Tools for Web Development 6) Introduction to HTML 7) History of HTML 8) The HTML specification 9) HTML Elements and Tags 10) Replaced Element and Void Element 11) Writing Accessible HTML 12) Validating HTML documents 13) HTML Resources and Reference 14) Introduction to CSS 15) History of CSS 16) The CSS Specification 17) CSS Properties 18) CSS Selectors 19) CSS Units 20) CSS Specificity 21) The CSS Cascade 22) CSS Inheritance 23) The CSS Box model 24) CSS Margin Collapse 25) CSS Positioning 26) CSS z-index 27) CSS colors 28) CSS Backgrounds 29) CSS Variables 30) CSS Floats 31) CSS Block Formatting Context 32) CSS Flexbox part 1 33) CSS Flexbox part 2 34) CSS Grid part 1 35) CSS Grid part 2 36) CSS Media Queries 37) CSS Typography 38) CSS Animations and Transitions 39) CSS Naming conventions 40) Writing maintainable CSS 41) CSS References and Resource 42) Introduction to JavaScript 43) History of JavaScript 44) The EcmaScript specification 45) Introduction to programming 46) JavaScript Variables 47) JavaScript Arrays 48) JavaScript Objects 49) JavaScript Numbers 50) JavaScript Conditionals 51) JavaScript Loops 52) JavaScript Functions 53) The Document Object Model 54) Introduction to Ajax 55) JavaScript References and Resource 56) Introduction to Web Design 57) History of web design 58) Site Layouts in CSS 59) Introduction to Responsive web design 60) Introduction to Progressive Enhancement 61) Introduction to User Interface design 62) Introduction to user experience design 63) Introduction to Web accessibility and usability 64) Introduction to Color theory 65) Web design References and resource 66) Series final project 67) Building your career as a developer

Posted on by:

ziizium profile

Habdul Hazeez

@ziizium

I teach and write code with interests in Web Development, Computer Security, and Artificial Intelligence.

Discussion

markdown guide