iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

  1. User does something (click, type, scroll).
  2. JavaScript fires an HTTP request.
  3. Server responds with data — JSON today, XML in the early 2000s.
  4. JavaScript updates a piece of the DOM.
  5. 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 machineOne function call
XML responseXMLres.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

PatternUse
JSON over fetchStandard REST APIs.
Server-Sent Events (EventSource)One-way streaming from server.
WebSocketTwo-way real-time.
WebRTC data channelsPeer-to-peer.
HTMX / Turbo / InertiaHigher-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());

Test yourself

Q1. Modern "AJAX" usually means…
Q2. The classic XHR has been superseded by…
Q3. One-way streaming from the server uses…

Discussion

Loading…