How does Ajax Work
Ajax, a term coined by Jesse James Garrett that became popular after the publication of the article Ajax: A New Approach to Web Applications in February 2005, is short for Asynchronous JavaScript and XML.
The normal behavior of the Internet that involves sending pages to the browser is completely changed by the use of Ajax.
Ajax has become commonplace with its integration in HTML 5 and JavaScript frameworks, and in fact, the interest of developers has moved to HTML 5 for its new tags and APIs that accompany it. Among these, WebSocket appears as the successor to Ajax, because it is a superior means of communication between an application and the server or the backend.
Note: This post has been updated to reflect modern practice. The original 2014 version centered on the raw
XMLHttpRequestobject and the Internet ExplorerActiveXObjectfallback. IE is now gone, and on today’s web most Ajax is written with the Promise-basedfetch()API andasync/await.XMLHttpRequestis kept here to explain the underlying mechanics, and a new “The Modern Way: fetch()” section has been added.
What’s Ajax?
Ajax is a set of technologies, supported by a web browser, including these elements:
- HTML for the interface.
- CSS for the look and feel.
- JavaScript (ECMAScript) for local processing and DOM (Document Object Model) to access data inside the page or to access elements of XML file read on the server.
- The XMLHttpRequest object is used to read or send data on the server asynchronously.
- PHP or another scripting language may be used on the server.
The word “asynchronous” means that the response from the server will be processed when available, without waiting and freezing the display of the page.
Dynamic HTML has the same purpose and is a set of standards: HTML, CSS, and JavaScript. This allows changing the display of the page from user commands or from text typed by the user.
Ajax is DHTML plus the XHR object to exchange data with the server.
How does it Work?
To get data on the server, XMLHttpRequest provides two methods:
- open: create a connection.
- send: send a request to the server.
Data furnished by the server will be found in the attributes of the XMLHttpRequest object:
- responseXML for an XML file
- responseText for plain text.
We have to wait for the data to be available to process it, and in this purpose, the state of availability of data is given by the readyState attribute of XMLHttpRequest.
States of readyState follow (only the last one is really useful):
- 0: not initialized.
- 1: connection established.
- 2: request received.
- 3: processing the response.
- 4: finished.
The XMLHttpRequest object
It allows interacting with servers through its methods and attributes.
Attributes
| Attribute | Description |
|---|---|
readyState | Successively changes value from 0 to 4; 4 means “ready”. |
status | 200 is OK; 404 if the page is not found. |
responseText | Holds loaded data as a string of characters. |
responseXML | Holds a loaded XML file; DOM methods allow extracting data. |
onreadystatechange | A function invoked whenever the readystatechange event is dispatched. |
Methods
| Method | Description |
|---|---|
open(mode, url, async) | mode: type of request, GET or POST. url: the location of the file, with a path. async: true (asynchronous) or false (synchronous, now deprecated on the main thread). Optionally, a login and a password may be added to the arguments. |
send(body) | Pass null for a GET request. |
How to Use it?
Ajax is used by defining JavaScript functions to use the XMLHttpRequest objects’ methods and attributes, or simply by installing a framework that defines the most common tasks.
These frameworks include a JavaScript code that runs client-side and possibly also codes in another programming language that runs server-side.
The role of the XHR object is to send requests to the server with the send function. The HTTP methods GET and POST as well as others, determine the nature of the request: GET to receive data, POST to send (and receive the result). The HEAD method gives information on the nature of a file on the server. The XHR object can receive text files, assigned to the responseText attribute, or XML assigned to responseXML.
Manually Using JavaScript
Create the Request
const xhr = new XMLHttpRequest();
Wait for Response
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
document.getElementById('result').textContent = 'Received: ' + xhr.responseText;
} else {
document.getElementById('result').textContent = 'Error code ' + xhr.status;
}
}
};
Make the Request
xhr.open('POST', '/login.do', true);
xhr.send('username=someone&password=passwd');
The Modern Way: fetch()
Modern browsers ship the fetch() API, which returns a Promise instead of relying on readyState callbacks. Combined with async/await, the three steps above collapse into a single, linear function:
async function login(username, password) {
const response = await fetch('/login.do', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ username, password }),
});
if (!response.ok) {
throw new Error(`Error code ${response.status}`);
}
return response.text(); // or response.json() for a JSON API
}
There is no manual state machine and no browser-detection branch: fetch() resolves once the response is ready, response.ok replaces the explicit status === 200 check, and the body is read with response.text() or response.json(). For new code, prefer fetch() over raw XMLHttpRequest.
Use a Framework
For many years, JavaScript frameworks wrapped these low-level details so you did not have to touch the XHR object directly.
- jQuery exposed
$.ajax()along with shorthands like$.get()and$.post(), and for a long time was the most common way to make Ajax calls. It still works but is now considered legacy. - Older libraries such as Rico and MooTools bundled Ajax helpers alongside widgets and special effects; both are long obsolete today.
Modern applications either call fetch() directly or use a thin wrapper such as axios, while single-page-application frameworks like React, Vue, and Angular build data fetching into their own tooling.
Evolution of Ajax
Should the word Ajax be restricted solely to the definition that was given by JJ Garrett in 2005 or can we use the term for new technologies intended to create dynamic web pages?
In fact, from the outset, the definition was too restrictive because XML is far from being the single or preferential format to exchange data with a server.
However, there are quantities of technologies to achieve modern web applications which must be distinguished from Ajax.
Therefore it is better to restrict the word to the use of XMLHttpRequest in combination with the dynamic-page technologies listed above, with any data format for exchanging data with the server.
We can consider that Ajax in the future will designate any mode of asynchronous communication and updating dynamic pages, even if it is based on a different object replacing XHR, but this object must work on all browsers because Ajax is founded in principle on standards.
Ajax is actually surpassed technologically by new protocols such as WebSocket which enables bidirectional communication (the server can send data itself) and WebRTC which goes further by providing real-time communication. But that does not mean that Ajax is useless in practice: very often it is more than enough to improve the user experience of an online application that depends on user actions.
A comparison of XMLHttpRequest and WebSocket is given in an article that explains how to use the XHR object and WebSocket, and the advantage of bidirectional exchanges over simple asynchronous protocol.
The Disqus comment system is loading ...
If the message does not appear, please check your Disqus configuration.