Skip to content

What is AJAX and Why Should I Care?

AJAX is the technique of requesting data from a server in the background, while the page stays open and usable, and then updating part of the page with the result. The name stands for Asynchronous JavaScript and XML, although today the data is almost always JSON rather than XML.

Before AJAX, every new piece of data meant loading a whole new page. With it, a search box can show suggestions as the user types, a basket can update its total without a reload, and a feed can load more items as the user scrolls.

The word asynchronous is the important part. The browser sends the request and carries on running the page, so the user can still scroll, click and type. When the response arrives, the browser runs the code that was waiting for it.

Current code makes requests with fetch(). It takes a URL and returns a promise, which resolves to a Response object once the server replies. Reading the body is a second asynchronous step, so response.json() returns another promise.

const response = await fetch('https://jsonplaceholder.typicode.com/todos/4');
const todo = await response.json();
console.log(`${todo.title} (done: ${todo.completed})`);

This prints:

et porro tempora (done: true)

The example uses JSONPlaceholder, a free service that returns sample data, and it uses top-level await, which works in modules and in the browser console. fetch() is built into every current browser and into Node.js 18 and later, so no library is needed. Fetch Method for AJAX covers it in detail, including the error handling that this short example leaves out.

Before fetch() existed, requests were made with the XMLHttpRequest object, usually shortened to XHR. It works with events rather than promises: the code creates the object, opens a request, attaches listeners for the outcome and then sends it. XHR exists only in browsers, so this example needs a page to run in.

<button id="load-todo">Load a task</button>
<p id="todo"></p>
const button = document.getElementById('load-todo');
const output = document.getElementById('todo');
button.addEventListener('click', () => {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/4');
xhr.responseType = 'json';
xhr.addEventListener('load', () => {
if (xhr.status === 200) {
output.textContent = xhr.response.title;
} else {
output.textContent = `The server replied with status ${xhr.status}`;
}
});
xhr.addEventListener('error', () => {
output.textContent = 'The request could not be sent';
});
xhr.send();
});

Clicking the button sends the request, and when the response arrives the paragraph shows the task’s title. The load listener reads the result from the xhr object itself, because the event passed to the listener does not carry the response. Setting responseType to 'json' makes the browser parse the body, so xhr.response is already an object.

open() takes an optional third argument, and passing false there makes the request synchronous. A synchronous request freezes the page until the server answers, which is why browsers deprecate it on the main thread, so leave the argument out.

Use fetch() in new code. It is shorter, it returns promises that work with async and await, and it is available outside the browser as well. XHR still works in every browser, so it is common in older code. The one thing it does that fetch() cannot do directly is report upload progress, which XHR offers through events on its upload property.

Whichever is used, a request can fail in two ways. The network can fail, so that no response arrives at all, or the server can reply with an error status such as 404 or 500. Code that only handles the first case will treat an error page as data.

Steve Griffith covers this topic in his video What is AJAX and Why Should I Care.