Before the Fetch API existed, every AJAX request used one browser object. It is still in use in older code, and understanding it shows exactly what happens during a request.
Making a Request
The XMLHttpRequest object is created with new XMLHttpRequest(). The method open("GET", "data.txt", true) sets the method and the address, and the value true makes the request asynchronous. The method send() starts it. For a POST request, the data is passed to send.
Definition: XMLHttpRequest. A built-in browser object used to send an HTTP request and receive the reply.
The readyState Property
A request moves through five stages, and the property readyState holds the current number. The function assigned to onreadystatechange runs each time the number changes.
Definition: readyState. A number from 0 to 4 that shows how far an XMLHttpRequest has progressed.
Table 4.6: The values of readyState
| Value | Name | Meaning |
|---|---|---|
| 0 | UNSENT | The object is created |
| 1 | OPENED | open has been called |
| 2 | HEADERS_RECEIVED | send called, headers received |
| 3 | LOADING | The reply is arriving |
| 4 | DONE | The operation is complete |
Status Codes
When readyState is 4, the status property tells whether the request worked. The code 200 means OK. The code 404 means the file was not found, and 500 means the server had an error. The text of the reply is in responseText. The handler should check both: readyState equal to 4 and status equal to 200, and it should show a message for any other status.
Example 4.6: Loading a text file
<div id="out"></div>
<script>
const out = document.getElementById("out");
const x = new XMLHttpRequest();
x.onreadystatechange = function () {
if (x.readyState !== 4) return;
if (x.status === 200) {
out.textContent = x.responseText;
} else {
out.textContent = "Error " + x.status;
}
};
x.open("GET", "notice.txt", true);
x.send();
</script>
When the file is found, its text appears in the div. If it is missing, the page shows Error 404.
Common mistakes
- Using the response without checking that readyState is 4 and status is 200.
- Assigning onreadystatechange after calling send, so the handler may be late.
- Passing false to open, which makes the request synchronous.
- Opening a page from the file system, where browsers often block requests, instead of from a server.
Key takeaways
- Create the object, call open, then call send.
- readyState runs from 0 to 4, and 4 means the request is complete.
- Check status 200 before using responseText, and report errors.
- Fetch is the newer, simpler tool, but XMLHttpRequest remains in older code.
Practice questions
- What does readyState 4 mean?
- Which status code means the file was not found?
- What does the third argument true of open mean?
Answers to the practice questions
- The request is complete.
-
- The request is asynchronous.
Sources
- Official BCA syllabus (NEP 2025 scheme), Web Application Development, course code 25BCA405DS04, Unit IV
