JavaScript AJAX & XMLHttpRequest: Asynchronous Architecture & Legacy Systems

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.

Classic XMLHttpRequest Implementation

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();
}

The 5 XHR readyState Values Table

ValueState ConstantOperational Meaning
0UNSENTXHR object instantiated, open() not yet invoked.
1OPENEDopen() has been invoked; request parameters configured.
2HEADERS_RECEIVEDsend() invoked; HTTP headers and status code received.
3LOADINGResponse body data stream currently downloading.
4DONEData transfer completely finished or failed.

University Exam Corner (BCA / B.Sc CS)

Exam Question: "Compare XMLHttpRequest (AJAX) and the modern Fetch API."

  • API Model: XHR is event-based (onreadystatechange, callbacks). Fetch is natively Promise-based and supports async/await.
  • Syntax: Fetch requires significantly less boilerplate code and avoids Callback Hell.
  • Upload Progress: XHR natively supports upload progress events (xhr.upload.onprogress), which is currently more complex with Fetch.

Next Step

What data interchange format powers virtually all web APIs today? Proceed to: JavaScript JSON: Parsing, Serialization & Security →

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!