AJAX in JavaScript
AJAX stands for Asynchronous JavaScript and XML. It describes a technique for loading data from a server in the background without refreshing the whole page.
The name is historical. Today we use JSON instead of XML, and we use fetch() instead of XMLHttpRequest. But the technique is still widely called AJAX.
How AJAX works
- The user does something on the page (clicks a button, scrolls, types in a search box).
- JavaScript sends a request to a server in the background.
- The server processes the request and sends back data.
- JavaScript updates part of the page with that data.
No full page reload happens. The user stays on the same page and only the relevant part updates.
This is how almost every modern web app works. Search suggestions, loading more posts as you scroll, form submission without a redirect, live notifications: all AJAX.
Modern AJAX with fetch()
The fetch() function is the standard way to make AJAX requests today. It returns a Promise.
async function loadUsers() {
const response = await fetch('https://api.github.com/users');
const users = await response.json();
console.log(users);
}
loadUsers();
With error handling:
async function loadUsers() {
try {
const response = await fetch('https://api.github.com/users');
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const users = await response.json();
return users;
} catch (err) {
console.error('Failed to load users:', err.message);
}
}
See the Fetch API page for full documentation including POST requests, headers, and error handling patterns.
Legacy: XMLHttpRequest
Before fetch() existed, AJAX was done with XMLHttpRequest (XHR). You will still see this in older codebases.
// Legacy approach: use fetch() in new code
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.github.com/users');
xhr.onload = function () {
if (xhr.status === 200) {
const users = JSON.parse(xhr.responseText);
console.log(users);
}
};
xhr.send();
XHR works, but it is more verbose and harder to read than fetch(). Use fetch() for all new code.