Skip to main content

AJAX and how it works

Short answer

AJAX uses XMLHttpRequest to send asynchronous HTTP requests. The server processes and returns data; the callback updates the DOM when readyState is 4 and status is 200, without reloading the page.

Briefly explain how AJAX request and response work.

AJAX (Asynchronous JavaScript and XML) is a technique that lets a web page send requests to the server and update parts of the page in the background, without reloading the whole page. It combines HTML/CSS, the DOM, JavaScript, the XMLHttpRequest object (or fetch) and data formats such as XML or JSON.

How the request and response work

  1. Event: A user action (click, key press, timer) triggers a JavaScript function.
  2. Create object: JavaScript creates an XMLHttpRequest object.
  3. Send request: open(method, url, async) and send() send an HTTP request to the server asynchronously; the page stays usable.
  4. Server processing: The server script (PHP, Servlet, etc.) processes the request, may query a database, and returns data (text, XML or JSON).
  5. Callback: When the response arrives, onreadystatechange fires. When readyState == 4 and status == 200, the response is ready.
  6. Update page: JavaScript reads responseText or responseXML and updates the DOM, changing only a part of the page.
Browser (JS)                     Server
  | -- XMLHttpRequest (async) -->  |
  |   (user keeps working)         | process
  | <-- response (JSON/XML/text) - |
  |  update DOM: only part changes |
function loadData() {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      document.getElementById("result").innerHTML = xhr.responseText;
    }
  };
  xhr.open("GET", "data.php?id=5", true);   // true = asynchronous
  xhr.send();
}

readyState values: 0 unsent, 1 opened, 2 headers received, 3 loading, 4 done.

Advantages: faster, less bandwidth, better user experience (Gmail, Google Maps, live search suggestions).

✓ Answer checked by Claude Opus 5.5 (high effort)

All Web Technology chapter 6 questions →