AJAX (Asynchronous JavaScript and XML)
1. What is AJAX?
AJAX is not a single technology but a group of client-side techniques for exchanging data with a server in the background without reloading the whole page. It combines: HTML/CSS (presentation), DOM (dynamic display/interaction), XMLHttpRequest (async data transfer), XML/JSON (data format), and JavaScript (glue).
Classic web: every click = full page request/response → flicker, wait. AJAX web: only the needed fragment is fetched and injected into the page → fast, app-like experience (Google Suggest, Gmail, Maps).
2. Synchronous vs Asynchronous Interaction
CLASSIC (synchronous): AJAX (asynchronous):
Browser Server Browser Server
|--request--->| |--request--->| (background
| wait... | | user keeps| XHR)
| (page | | working |
| frozen) | |<--fragment--|
|<--full page-| | DOM update |
3. XMLHttpRequest — Lifecycle
- Create an
XMLHttpRequestobject. - Register a callback for the
onreadystatechangeevent. open(method, url, async)— configure the request.- Optionally set request headers;
send(data). - Server responds;
readyStatebecomes 4,status200 → readresponseText/responseXMLand update the DOM.
readyState values: 0 = uninitialised, 1 = loading (open called), 2 = loaded (send called), 3 = interactive (receiving), 4 = completed. Check status == 200 for OK.
var xhr = new XMLHttpRequest(); // 1
xhr.onreadystatechange = function () { // 2
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("result").innerHTML = xhr.responseText; // 5
}
};
xhr.open("GET", "checkuser.jsp?name=" + encodeURIComponent(name), true); // 3
xhr.send(null); // 4
9. Advantages and Limitations
Advantages
- No page reload — only the required data/fragment is transferred → less bandwidth, faster response.
- Rich, responsive UI — continuous user interaction while requests run in background; server load reduced (small payloads).
- Standard technologies only (no plug-in); works with any server technology (JSP/PHP/ASP).
Limitations
- Browser history/back button and bookmarking break for dynamically changed content; same-origin policy restricts cross-domain XHR.
- Search engines may not index AJAX content; harder debugging; JavaScript-disabled browsers get nothing; many small requests can overwhelm the server if poorly designed.
10. Exam Points
- What is AJAX? Explain its component technologies and advantages over the classic request/response model — 10 marks (very frequent).
- Explain
XMLHttpRequestwith readyState/status values and write a live example (username check / drop-down fill / live search) — 10 marks program. - AJAX vs traditional web application — 5 marks.
- Short notes: JSON as an AJAX data format, same-origin policy — 3-5 marks.