Coined in 2005 by Jesse James Garrett, AJAX (Asynchronous JavaScript and XML) revolutionized web browsing. Prior to AJAX, every single user action required the browser to request and reload a completely new HTML page. AJAX introduced background data fetching using the XMLHttpRequest (XHR) object, birthing modern single-page applications.
function loadDataUsingXHR(url) {
// 1. Create a new XHR instance
const xhr = new XMLHttpRequest();
// 2. Initialize request: method, URL, asyncFlag
xhr.open("GET", url, true);
// 3. Register state change event listener
xhr.onreadystatechange = function() {
// readyState 4 === DONE; status 200 === HTTP OK
if (xhr.readyState === 4) {
if (xhr.status === 200) {
const responseData = JSON.parse(xhr.responseText);
console.log("XHR Data Received:", responseData);
} else {
console.error("XHR Request Failed with Status:", xhr.status);
}
}
};
// 4. Dispatch the request
xhr.send();
}
| Value | State Constant | Operational Meaning |
|---|---|---|
| 0 | UNSENT | XHR object instantiated, open() not yet invoked. |
| 1 | OPENED | open() has been invoked; request parameters configured. |
| 2 | HEADERS_RECEIVED | send() invoked; HTTP headers and status code received. |
| 3 | LOADING | Response body data stream currently downloading. |
| 4 | DONE | Data transfer completely finished or failed. |
Exam Question: "Compare XMLHttpRequest (AJAX) and the modern Fetch API."
onreadystatechange, callbacks). Fetch is natively Promise-based and supports async/await.xhr.upload.onprogress), which is currently more complex with Fetch.What data interchange format powers virtually all web APIs today? Proceed to: JavaScript JSON: Parsing, Serialization & Security →