Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Explain the different ready states of a request in AJAX
AJAX stands for Asynchronous JavaScript and XML. It is a set of web development techniques to create interactive web applications. AJAX allows a web page to communicate with a server without reloading the page.
Ready states are an important part of working with AJAX requests. The ready state of a request indicates the request's status to the server and allows the client to track the progress of the request through the readyState property of the XMLHttpRequest object.
In the below sections, we detail the different ready states of AJAX requests.
UNSENT STATE (0)
This is the initial ready state of AJAX requests. It is denoted by the integer 0. When creating an XMLHttpRequest object, the request starts in the "unsent" state until the open() method is called. This means that the request has not been initialized yet. This state is also referred to as XMLHttpRequest.UNSENT.
Syntax
http.onreadystatechange = function () {
if (this.readyState == 0) {
// This state is rarely used in practice
console.log('This is UNSENT state');
}
}
OPENED STATE (1)
This is the second ready state of AJAX requests, denoted by the integer 1. The opened state occurs when the open() method has been called, but send() has not been called yet. This indicates that the request has been initialized and is ready to be sent, but the actual HTTP request hasn't been dispatched to the server.
For example, after calling xhr.open('GET', '/api/data'), the request enters this state and remains here until xhr.send() is called.
Syntax
http.onreadystatechange = function () {
if (this.readyState == 1) {
console.log('This is OPENED state');
}
}
HEADERS_RECEIVED STATE (2)
This is the third ready state of AJAX requests, denoted by the integer 2. The Headers Received state occurs when the request has been sent to the server, and the server has responded with HTTP headers. The server has acknowledged the request and sent back response headers, but the response body is not yet available.
At this point, you can access response headers using methods like getResponseHeader() or getAllResponseHeaders(). The status code is also available.
Syntax
http.onreadystatechange = function () {
if (this.readyState == 2) {
console.log('This is HEADERS_RECEIVED state');
console.log('Status:', this.status);
}
}
LOADING STATE (3)
The loading state occurs when the response body is being downloaded from the server. During this state, the responseText property contains partial data if the response is text-based. This state may occur multiple times as data chunks are received.
For example, when downloading a large JSON response, this state allows you to track the download progress and potentially process data as it arrives.
Syntax
http.onreadystatechange = function () {
if (this.readyState == 3) {
console.log('This is LOADING state');
// Partial response may be available
}
}
DONE STATE (4)
The done state indicates that the request has been completed successfully or failed. The server has sent the complete response, and all data is available for processing. At this point, you can safely access the full response data through responseText, responseXML, or response properties.
Syntax
http.onreadystatechange = function () {
if (this.readyState == 4) {
console.log('This is DONE state');
if (this.status == 200) {
// Process successful response
console.log(this.responseText);
}
}
}
Complete Example
Here's a complete example demonstrating all AJAX ready states in action:
<html>
<body>
<h2>Different <i>Ready States</i> of AJAX</h2>
<button onclick="ajaxCall()">Trigger AJAX Call</button>
<div id="root" style="border: 1px solid black; padding: 10px; margin-top: 10px;"></div>
<script>
let root = document.getElementById('root');
function ajaxCall() {
root.innerHTML = 'AJAX Call Started!<br><br>';
// Create XMLHttpRequest object
let http = new XMLHttpRequest();
// Set up event handler for ready state changes
http.onreadystatechange = function () {
if (this.readyState == 1) {
root.innerHTML += 'Ready State 1: OPENED - Request initialized<br>';
}
if (this.readyState == 2) {
root.innerHTML += 'Ready State 2: HEADERS_RECEIVED - Headers received<br>';
}
if (this.readyState == 3) {
root.innerHTML += 'Ready State 3: LOADING - Response body loading<br>';
}
if (this.readyState == 4) {
root.innerHTML += 'Ready State 4: DONE - Request completed<br>';
if (this.status == 200) {
root.innerHTML += '<br>? AJAX Call Successful!<br>';
root.innerHTML += 'Response received: ' + this.responseText.substring(0, 100) + '...';
} else {
root.innerHTML += '<br>? AJAX Call Failed with status: ' + this.status;
}
}
};
// Initialize the request
http.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
// Send the request
http.send();
}
</script>
</body>
</html>
Ready State Summary
| State | Value | Description | Data Available |
|---|---|---|---|
| UNSENT | 0 | XMLHttpRequest created, not initialized | None |
| OPENED | 1 | open() called, ready to send | None |
| HEADERS_RECEIVED | 2 | Headers received from server | Headers, Status |
| LOADING | 3 | Response body downloading | Partial response |
| DONE | 4 | Request completed | Full response |
Conclusion
Understanding AJAX ready states is crucial for building robust web applications. The five ready states (0-4) track the complete lifecycle of an XMLHttpRequest, from initialization to completion. Most practical applications focus on the DONE state (4) for processing responses, but monitoring other states can provide valuable feedback for user experience and error handling.
