AJAX Intro
AJAX ("Asynchronous JavaScript And XML") is the technique of updating the page from server data without a full reload. Modern AJAX uses fetch + JSON — the XML in the name is purely historical.
The original idea
- User does something (click, type, scroll).
- JavaScript fires an HTTP request.
- Server responds with data — JSON today, XML in the early 2000s.
- JavaScript updates a piece of the DOM.
- The rest of the page stays put.
Old vs. modern
| Old (XHR + XML) | Modern (fetch + JSON) |
|---|---|
new XMLHttpRequest() | fetch() |
Callbacks (onreadystatechange) | Promises / async-await |
| Verbose state machine | One function call |
| XML responseXML | res.json() / res.text() |
Modern AJAX in 5 lines
JS
async function loadUsers() {
const res = await fetch("/api/users");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const users = await res.json();
render(users);
}
Wider patterns
| Pattern | Use |
|---|---|
| JSON over fetch | Standard REST APIs. |
Server-Sent Events (EventSource) | One-way streaming from server. |
| WebSocket | Two-way real-time. |
| WebRTC data channels | Peer-to-peer. |
| HTMX / Turbo / Inertia | Higher-level libraries that swap HTML fragments. |
Tip: "AJAX" today usually means "the page updates without reloading". The transport is fetch, the format is JSON, the term sticks around for the technique.
Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from AJAX Intro!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Make the modern AJAX call: GET the users JSON.
const users = await
('/api/users').then(r => r.json());
Five letters.
Discussion
Loading…