- Asked 3/4
- 2068 Chaitra (old course) · 5 marks
- 2074 Asoj · 3 marks
- Year not given · 2.5 marks
- 2074 Chaitra
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
- Event: A user action (click, key press, timer) triggers a JavaScript function.
- Create object: JavaScript creates an
XMLHttpRequestobject. - Send request:
open(method, url, async)andsend()send an HTTP request to the server asynchronously; the page stays usable. - Server processing: The server script (PHP, Servlet, etc.) processes the request, may query a database, and returns data (text, XML or JSON).
- Callback: When the response arrives,
onreadystatechangefires. WhenreadyState == 4andstatus == 200, the response is ready. - Update page: JavaScript reads
responseTextorresponseXMLand 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)
Related questions
- DNS request/response structure · Computer Networks and Security, chapter 6
- CGI working; JSP vs ASP; AJAX · Internet and Intranet, chapter 6
- Recursive function and how it works · Computer Programming, chapter 6 · asked 3×
- Building: excavation, PCC, brick, wood work · Estimating and Costing, chapter 6