← Back to JavaScript Course | Chapter 9: Async & Web APIs | Lesson 10 of 26

JS AJAX

The Fetch API topic already covers the modern way to make background HTTP requests, but AJAX (Asynchronous JavaScript and XML) is the older, broader technique that predates fetch by over a decade, originally built on the XMLHttpRequest object. Many existing codebases, tutorials, and interview questions still reference AJAX and XMLHttpRequest directly, making it worth understanding even though fetch is now preferred for new code.

What AJAX Means

AJAX stands for Asynchronous JavaScript and XML, though modern AJAX overwhelmingly exchanges JSON rather than actual XML -- the core idea is a background request to a server that updates part of a page without triggering a full reload, the same technique fetch() implements in a more modern way.

Note: Think of AJAX as a technique or pattern, not a specific API -- both the old XMLHttpRequest object and the modern fetch() function are ways of "doing AJAX".

Warning: The "XML" in AJAX is largely a historical artifact from when XML was the dominant data format for these requests -- do not assume an AJAX request must involve actual XML today.

Example: What AJAX Means

javascript
// AJAX: background request updates part of a page, no full reload
fetch("data.php")
  .then(response => response.json())
  .then(data => console.log(data)); // modern AJAX exchanges JSON, not XML

XMLHttpRequest: The Original AJAX API

Before fetch() existed, XMLHttpRequest was the only way to make a background HTTP request from JavaScript -- it works by creating an XMLHttpRequest object, configuring an event listener for when the response arrives, and calling .send() to actually fire off the request.

Note: Recognize the XMLHttpRequest pattern (new XMLHttpRequest(), .open(), .onreadystatechange, .send()) when reading older code, even if you write new code with fetch instead.

Warning: XMLHttpRequest's callback-based, readyState-checking style is noticeably more verbose than the promise-based fetch API for accomplishing the same request.

Example: XMLHttpRequest: The Original AJAX API

javascript
const xhr = new XMLHttpRequest();
xhr.addEventListener("load", () => console.log(xhr.responseText));
xhr.open("GET", "data.php");
xhr.send();

Why fetch() Largely Replaced XMLHttpRequest

fetch() returns a Promise, integrating naturally with .then()/.catch() chains and async/await, while XMLHttpRequest relies on manually checking readyState inside an event callback -- fetch's cleaner syntax is why it has become the default choice for new AJAX-style code.

Note: Default to fetch() for all new code; reserve XMLHttpRequest knowledge specifically for reading, maintaining, or debugging existing code that already uses it.

Warning: fetch() does not reject its promise on an HTTP error status (like 404 or 500) the way you might expect -- checking response.ok is still necessary, a subtlety worth remembering from either API.

Example: Why fetch() Largely Replaced XMLHttpRequest

javascript
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => { if (xhr.readyState === 4) console.log(xhr.responseText); };
xhr.open("GET", "data.php");
xhr.send();

fetch("data.php").then(r => r.json()).then(data => console.log(data));

Where AJAX Fits in a Web Application

AJAX-style requests (via fetch or XMLHttpRequest) power live search, form submission without a reload, infinite-scrolling feeds, real-time dashboard updates, and any interaction where reloading the entire page would feel slow or jarring for what is really a small data update.

Note: Reserve AJAX for interactions that genuinely benefit from feeling instant and partial, rather than converting every page interaction into a background request unnecessarily.

Warning: An AJAX-dependent feature that fails silently when JavaScript errors or network requests fail can leave a user stuck with no visible feedback -- always handle the failure case.

Example: Where AJAX Fits in a Web Application

javascript
function search(term) {
  fetch(`search.php?term=${term}`).then(r => r.json()).then(results => console.log(results));
}
search("widgets");

AJAX and Server-Side Languages

AJAX requests are language-agnostic on the client side -- JavaScript sends the request the same way regardless of what powers the server responding to it, whether that is PHP, Node.js, Python, or any other backend -- as long as the server returns an appropriate response the JavaScript can parse.

Note: Confirm the server endpoint's expected request format (query string, JSON body, form data) and response format before wiring up the client-side fetch or XMLHttpRequest code.

Warning: A mismatch between what the client sends (like JSON) and what the server expects (like form-encoded data) is a very common source of "why is my AJAX request failing" bugs.

Example: AJAX and Server-Side Languages

javascript
fetch("data.php").then(r => r.json()).then(data => console.log(data)); // could be PHP, Node.js, Python, etc.
Common Mistakes
  1. Assuming AJAX and XMLHttpRequest are obsolete and can be skipped entirely -- a significant amount of existing production code still uses XMLHttpRequest directly, especially in older libraries and frameworks.
  2. Confusing AJAX (the general technique) with XMLHttpRequest (one specific, older API for implementing it) -- fetch is also a way of doing AJAX, just a newer one.
  3. Writing new code with XMLHttpRequest out of habit or old tutorials, when fetch offers a cleaner, promise-based API for the same job in modern browsers.
Chapter Summary
  • AJAX describes the technique of making a background HTTP request without a full page reload -- both XMLHttpRequest and fetch are ways of doing AJAX.
  • XMLHttpRequest is the original browser API for AJAX, using an event-based callback style rather than promises.
  • For new code, fetch() is generally preferred over XMLHttpRequest for its simpler, promise-based syntax -- but understanding XMLHttpRequest remains valuable for reading existing code.
Browser Support

XMLHttpRequest has been supported in every browser since the early 2000s; fetch is supported in all current browsers as the modern replacement.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.