← 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.
Syntax
javascript
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function() {
  // xhr.responseText
};
xhr.send();

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.

उदाहरण: 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.

उदाहरण: XMLHttpRequest: The Original AJAX API

javascript
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
const xhr = new XMLHttpRequest();
// Listen for the `load` event on `xhr` and run the handler when it fires
// Listen for the `load` event on `xhr` and run the handler when it fires
xhr.addEventListener("load", () => console.log(xhr.responseText));
// Call `xhr.open("GET", "data.php")`
// Call `xhr.open("GET", "data.php")`
xhr.open("GET", "data.php");
// Call `xhr.send()`
// Call `xhr.send()`
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.

उदाहरण: Why fetch() Largely Replaced XMLHttpRequest

javascript
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
const xhr = new XMLHttpRequest();
// Assign `() => { if (xhr.readyState === 4) console.log(xhr.responseText); }` to `xhr.onreadystatechange`
// Assign `() => { if (xhr.readyState === 4) console.log(xhr.responseText); }` to `xhr.onreadystatechange`
xhr.onreadystatechange = () => { if (xhr.readyState === 4) console.log(xhr.responseText); };
// Call `xhr.open("GET", "data.php")`
// Call `xhr.open("GET", "data.php")`
xhr.open("GET", "data.php");
// Call `xhr.send()`
// Call `xhr.send()`
xhr.send();

// Call `fetch("data.php").then(r => r.json()).then(data => console.log(data))`
// Call `fetch("data.php").then(r => r.json()).then(data => console.log(data))`
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.

उदाहरण: Where AJAX Fits in a Web Application

javascript
// Define the function `search` taking `term`
// Define the function `search` taking `term`
function search(term) {
  fetch(`search.php?term=${term}`).then(r => r.json()).then(results => console.log(results));
}
// Call `search("widgets")`
// Call `search("widgets")`
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.

उदाहरण: 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.
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

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.