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.
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.
Switch over to your browser and navigate to this newly created directory as depicted in the image below.
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.
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:
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.
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.
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.