AJAX (Asynchronous JavaScript and XML) lets a page exchange data with the server in the background and update only part of the DOM, without reloading. XMLHttpRequest, readyState and status, JSON, fetch with promises, and the same-origin policy with CORS are the essentials.
High-yield 55 minSyllabus: “AJAX”
Mark as
The idea in one minute
Ordering food the old way means walking to the counter for every item, waiting, and coming back to a table that has been cleared — a full page reload each time. AJAX is a waiter who carries a small note to the kitchen while you keep talking, then quietly places just the new dish on your table. Everything else — your half-filled form, your scroll position — stays exactly as it was.
Key points — the night-before list
AJAX = Asynchronous JavaScript and XML, named by Jesse James Garrett in 2005 — a technique, not a language: HTML/CSS + DOM + XMLHttpRequest + XML/JSON + JavaScript.
Classic model: every action reloads the whole page. AJAX model: JavaScript sends a background request and updates part of the DOM while the user keeps working.
fetch() returns a promise that rejects only on network failure — a 404 or 500 still resolves, with response.ok false. Read JSON with await response.json().
Same-origin policy: scheme, host and port must all match. Cross-origin reads need CORS headers (Access-Control-Allow-Origin); non-simple requests are preflighted with OPTIONS. JSONP was the old workaround.
Pros: responsive UI, less data transferred, partial updates. Cons: Back button and bookmarks, SEO, accessibility, JavaScript dependence. Classic uses: Gmail, Google Maps, search suggestions.
01What AJAX is
AJAX stands for Asynchronous JavaScript and XML. Jesse James Garrett of Adaptive Path coined the name in his February 2005 essay Ajax: A New Approach to Web Applications, describing how Google Suggest, Gmail and Google Maps behaved like desktop programs inside a browser. AJAX is not a language or a product but a combination of existing technologies:
HTML/XHTML and CSS — the presentation.
The DOM — so JavaScript can change part of the page.
XMLHttpRequest (or today fetch) — to talk to the server asynchronously.
XML or JSON — the format of the data exchanged (JSON now dominates despite the X in the name).
JavaScript — the glue that ties them together.
The key object is older than the name. Microsoft's Outlook Web Access team created the XMLHTTP ActiveX object, shipped with Internet Explorer 5 in 1999; Mozilla added a native XMLHttpRequest in 2002, Safari and Opera followed, and W3C began standardising it in 2006 (it is now a WHATWG living standard). Asynchronous means the script sends the request and carries on immediately; a callback runs later, when the answer arrives, so the page never freezes.
PSC favourite
The object that updates part of a web page without disrupting what the user is doing is XMLHttpRequest (asked in 2026 — not 'HttpRequest', $_GET or $_REQUEST).
02Classic web model vs AJAX model
Classic (synchronous) model
Each click or submit sends an HTTP request for a whole new page
The user waits on a blank or frozen screen — click, wait, refresh
The server re-sends HTML, menus and layout every time
Form contents and scroll position are lost unless rebuilt by the server
AJAX (asynchronous) model
JavaScript sends a small request in the background
The user keeps typing or scrolling while it is in flight
The server returns only data (JSON, XML or an HTML fragment)
JavaScript updates just the affected element in the DOM
One AJAX round trip
Event
Something happens in the page — a key press, a click, a timer.
Request
A handler creates an XMLHttpRequest (or calls fetch) and sends a request in the background.
Server
The server-side code (PHP, ASP.NET, Java…) does its work, perhaps queries a database, and returns data.
Callback
When the response arrives, the browser runs the callback function.
Update
The callback reads the data and changes only part of the DOM — no reload, no lost input.
Switch the Client–server tiers tool on this page to its AJAX mode to watch the small background request travel to the server and back while the rest of the page stays put.
Create the object (very old IE used new ActiveXObject("Microsoft.XMLHTTP"))
open(method, url, async)
Prepare the request: method (GET, POST…), URL, and true for asynchronous (the default); optional user and password
setRequestHeader(name, value)
Add a header such as Content-Type — only after open() and before send()
send(body)
Send it: null/nothing for GET, a string or FormData for POST
abort()
Cancel the request
readyState
Progress of the request, 0 to 4 (table below)
status, statusText
HTTP status code (200, 404…) and its text; 0 until the response headers arrive, or after a network error
responseText
Response body as a string
responseXML
Response parsed as an XML DOM document (when the server sent XML)
response, responseType
Body in the requested form: "text", "json", "document", "blob", "arraybuffer"
getResponseHeader(name)
Read one response header (getAllResponseHeaders() for all)
timeout, withCredentials
Time limit in ms; whether to send cookies on cross-origin requests
onreadystatechange
Callback fired every time readyState changes
onload, onerror, onprogress, ontimeout
Newer event handlers for completion, network failure, download progress and timeouts
readyState
Name
Meaning
0
UNSENT
Object created; open() not called yet
1
OPENED
open() has been called; headers can be set and send() called
2
HEADERS_RECEIVED
send() was called and the status line and response headers have arrived
3
LOADING
The body is downloading; responseText holds the part received so far (may fire repeatedly)
4
DONE
The operation is complete — successfully or not (check status)
So the classic test if (xhr.readyState === 4 && xhr.status === 200) means the request has completed and the server answered OK. readyState 4 alone is not enough: a 404 or 500 response also reaches DONE. Passing false as the third argument of open() makes the call synchronous — send() blocks until the response arrives and the page freezes — which is deprecated on the main thread.
04A complete example: live username check
On the housing portal's registration page, the browser tells applicants whether a username is free while they type. Three pieces are needed: the form field, the JavaScript, and a small server endpoint that answers in JSON.
// check.js
const nameInput = document.getElementById("username");
const statusEl = document.getElementById("status");
let timer = null;
nameInput.addEventListener("input", () => {
clearTimeout(timer); // debounce: wait until typing pauses
timer = setTimeout(checkName, 300);
});
function checkName() {
const name = nameInput.value.trim();
if (name.length < 3) { statusEl.textContent = ""; return; }
const xhr = new XMLHttpRequest();
xhr.open("GET", "check-username.php?u=" + encodeURIComponent(name), true); // true = asynchronous
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) { // 4 = DONE
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
statusEl.textContent = data.available ? "✓ available" : "✗ already taken";
statusEl.className = data.available ? "ok" : "bad";
} else {
statusEl.textContent = "Server error " + xhr.status;
}
}
};
xhr.send(); // a GET request has no body
statusEl.textContent = "checking…"; // runs at once: send() does not wait for the reply
}
PHP
<?php
// check-username.php — answers the AJAX call with JSON
require "db.php"; // the PDO connection from the PHP topic
header("Content-Type: application/json");
$u = trim($_GET["u"] ?? "");
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
$stmt->execute([$u]);
$taken = $stmt->fetchColumn() > 0;
echo json_encode(["username" => $u, "available" => !$taken]);
// for example: {"username":"anil","available":false}
encodeURIComponent makes spaces, & and other special characters safe inside the query string.
The server still uses a prepared statement — AJAX requests are ordinary HTTP requests that anyone can forge.
textContent (not innerHTML) puts the message into the page, so no server text can inject markup.
The final registration must still check the username again on the server: the live check is only a convenience.
05JSON responses and the fetch API
When the server sends XML, responseXML gives a DOM document to walk with getElementsByTagName. With JSON, JSON.parse(xhr.responseText) (or responseType = "json") gives JavaScript objects directly, which is why JSON replaced XML in most AJAX code. The modern fetch API does the same job with promises instead of readyState callbacks.
JavaScript
const list = document.getElementById("suggestions");
async function suggest(prefix) {
try {
const res = await fetch("suggest.php?q=" + encodeURIComponent(prefix));
if (!res.ok) { // 404 or 500 do NOT reject the promise
throw new Error("HTTP " + res.status);
}
const names = await res.json(); // e.g. ["Sneha Nagar", "Snehatheeram"]
list.replaceChildren(...names.map((n) => {
const li = document.createElement("li");
li.textContent = n; // text, not HTML: no XSS
return li;
}));
} catch (err) { // network failure, or the error thrown above
list.textContent = "Could not load suggestions (" + err.message + ")";
}
}
JavaScript
// the same request written with then() chains
fetch("schemes.json")
.then((res) => res.json())
.then((data) => console.log(data.length + " schemes"))
.catch((err) => console.error("Network error", err));
// sending JSON with POST (inside an async function or a module)
const res = await fetch("/api/applications", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ schemeId: 7, members: 4 }),
credentials: "same-origin", // send cookies (the default for same-origin requests)
});
const saved = await res.json();
With fetch(), a 404 does not trigger catch: the then() / await continues with response.ok === false (asked in 2025). Only a network failure (or an abort) rejects the promise.
06Same-origin policy, CORS and JSONP
Browsers enforce the same-origin policy: a script may freely read responses only from its own origin — the combination of scheme, host and port. It can still send many requests elsewhere, but cannot read the answers, which stops a malicious page from silently reading your bank statement using your cookies.
Request from https://portal.kshb.example
Same origin?
Why
https://portal.kshb.example/api/schemes
Yes
Same scheme, host and port
https://portal.kshb.example:443/api
Yes
443 is the default port for https
http://portal.kshb.example/api
No
Different scheme
https://api.kshb.example/schemes
No
Different host (a subdomain counts as different)
https://portal.kshb.example:8443/api
No
Different port
CORS (Cross-Origin Resource Sharing) lets a server opt in to cross-origin access. The browser adds an Origin header; the server answers with Access-Control-Allow-Origin naming that origin (or * for public data). Simple requests — GET, HEAD or POST with a form-style content type (application/x-www-form-urlencoded, multipart/form-data, text/plain) and no custom headers — are sent directly. Anything else, such as PUT, DELETE or a JSON body, is first checked with a preflight OPTIONS request.
TextOnly after this approval does the browser send the real POST; Max-Age lets it skip the preflight for 10 minutes
OPTIONS /api/applications HTTP/1.1 (preflight, sent automatically by the browser)
Origin: https://portal.kshb.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://portal.kshb.example
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 600
With Access-Control-Allow-Credentials: true (needed when the request carries cookies), the allowed origin must be named explicitly — the wildcard * is not accepted. Before CORS existed, sites used JSONP (JSON with Padding): since <script> tags may load code from any origin, the page adds <script src="https://api.other.example/schemes?callback=show"> and the server replies with JavaScript such as show([…]). JSONP supports only GET and runs whatever code the other server returns, so CORS has replaced it.
07Advantages, disadvantages and real uses
Advantages
Faster, smoother interaction — no full reloads
Less bandwidth: only data travels, not whole pages
Lower server load for small updates
Asynchronous: the UI stays usable while waiting
Desktop-like rich internet applications
Disadvantages
Back button and bookmarks may not reflect the page state (fix with the History API)
Content loaded by scripts can be missed by search engines (SEO)
Accessibility: screen readers must be told about updates (ARIA live regions)
Fails without JavaScript; harder to debug
More requests and a larger attack surface (XSS, CSRF, exposed endpoints)
Gmail (2004) — new mail appears and messages open without page reloads.
Google Maps (2005) — map tiles load in the background as you drag.
Google Suggest and every search box — suggestions while you type.
Live form checks (username availability), infinite scrolling, like buttons, live scores, chat (better done with WebSockets or SignalR).
08Patterns and pitfalls: debouncing, polling, stale replies and security
Debouncing waits until the user pauses before sending, as check.js does with a 300 ms timer: typing 'thrissur' quickly sends one request instead of eight. Polling asks the server repeatedly whether anything changed — simple, but wasteful and always a little late; for true push use WebSockets or SignalR (next topic).
JavaScript
// polling: ask every 10 s until the application is allotted
const poll = setInterval(async () => {
const res = await fetch("status.php?app=42");
const s = await res.json();
document.getElementById("appStatus").textContent = s.status;
if (s.status === "Allotted") clearInterval(poll);
}, 10000);
// stale replies: replies can arrive out of order, so cancel the previous request
let controller = null;
async function search(q) {
if (controller) controller.abort();
controller = new AbortController();
try {
const res = await fetch("suggest.php?q=" + encodeURIComponent(q), { signal: controller.signal });
showSuggestions(await res.json());
} catch (e) {
if (e.name !== "AbortError") throw e; // an aborted request is expected, not an error
}
}
Out-of-order replies — a slow answer for 'thr' may arrive after the answer for 'thrissur'; abort old requests or ignore replies that are no longer current.
CSRF — AJAX POSTs carry cookies too; send an anti-CSRF token (for example in an X-CSRF-Token header) and use SameSite cookies.
XSS — insert server data with textContent or build elements; never pass untrusted text to innerHTML.
Every endpoint is public — check authentication, authorisation and input on the server exactly as for normal pages.
Feedback — show a spinner or 'checking…', disable buttons while saving, and handle errors visibly.
Step through · A live username check with XMLHttpRequest
step 1 / 10
Step 1: Types 'anil' (input events)
Each key press fires an input event; the handler restarts a 300 ms debounce timer.
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Tracing readyState
A script assigns xhr.onreadystatechange = () => console.log(xhr.readyState, xhr.status); and then calls xhr.open("GET", "schemes.json", true); xhr.send();. (a) What is logged for a small, successful response? (b) What changes if the handler is assigned after open()? (c) What is the last line logged if the file does not exist? (d) And if the network is down?
EX 2Same origin, CORS and preflight
A page at https://portal.kshb.example calls three URLs with fetch: (a) https://portal.kshb.example/api/schemes (GET); (b) https://api.kshb.example/schemes (GET, no custom headers); (c) https://api.kshb.example/applications (POST with Content-Type: application/json, sending cookies with credentials: "include"). For each, is CORS involved, is there a preflight, and what must the API server send?
EX 3How much does AJAX save?
Before AJAX, checking a username meant submitting the form and reloading a 120 KB page; the AJAX version exchanges about 0.3 KB per check. (a) Compare the data transferred for 1,000 checks. (b) An applicant quickly types the 9-letter name 'sreekumar' (no pause longer than 300 ms) and stops. Ignoring checkName()'s 3-letter minimum, how many requests does the check send without and with a 300 ms debounce?
EX 4Rewriting XMLHttpRequest code with fetch
Rewrite the checkName() request from the username example with fetch and async/await, keeping the same behaviour, and say what the user sees if check-username.php is missing (404) and if the network is down.
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
Write XMLHttpRequest code that POSTs the fields scheme=7 and members=4 as form data to save.php and shows the server's text reply in the element with id msg. Where exactly must setRequestHeader go?
Q2
A log shows readyState values 2 3 3 3 4, with status 200 at the end. Explain each value, why 3 appears three times, and why 1 is missing.
Q3
An API at https://api.kshb.example must accept PUT requests with a JSON body and the user's cookies from pages on https://portal.kshb.example. Write the headers its preflight response must contain.
Q4
Why does this print undefined, and how do you fix it? let data; fetch("schemes.json").then(r => r.json()).then(j => { data = j; }); console.log(data);
Q5
A box uses a 300 ms debounce. How many requests are sent when a user types 12 letters with 150 ms between key presses and then stops? What if the gap is 400 ms? And with a 100 ms debounce and 150 ms gaps?
Exam traps
readyState 4 means finished, not successful — always check the status (200) as well.
fetch() does not reject on HTTP errors such as 404 or 500; test response.ok.
Same origin needs scheme, host and port to match: http vs https, a different subdomain or :8443 vs :443 all make a request cross-origin.
CORS is enforced by the browser; the server's headers only tell the browser whether the script may read the response. Tools such as curl ignore CORS completely.
Despite the X, AJAX does not require XML — JSON, HTML fragments or plain text work just as well.
Passing false to open() makes the request synchronous and freezes the page; 'asynchronous' is the A in AJAX.
Quiz — KPSC style
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
AJAX & XMLHttpRequest · Question 1 of 12✓ 0 · ✗ 0
The term AJAX was coined in 2005 by:
Past-paper questions on this topic
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
Past papers · Question 1 of 5✓ 0 · ✗ 0
Modelled on QP 050/2026 · Deputy Manager (IT) / Assistant Programmer / Computer Programmer etc (20 May 2026), Q.63 (reworded)original paper (PDF)
Which browser object lets a script refresh one part of a page in the background, without interrupting what the user is doing?