JS AJAX
In this page:
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
// 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
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
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
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
fetch("data.php").then(r => r.json()).then(data => console.log(data)); // could be PHP, Node.js, Python, etc.
- 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.
- 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.
- 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.
- 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.
XMLHttpRequest has been supported in every browser since the early 2000s; fetch is supported in all current browsers as the modern replacement.
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML