AJAX XMLHttpRequest
The foundation of AJAX communication
📦 What is XMLHttpRequest?
XMLHttpRequest (XHR) is a JavaScript object that enables communication with servers. It's the core technology behind AJAX, allowing you to send and receive data without refreshing the page.
// Create XMLHttpRequest object
const xhr = new XMLHttpRequest();
console.log(xhr); // XMLHttpRequest object
XMLHttpRequest Properties
readyState
Current state of the request (0-4)
xhr.readyState // 0 to 4
status
HTTP status code (200, 404, etc.)
xhr.status // 200
responseText
Response data as text string
xhr.responseText
statusText
Status message (OK, Not Found)
xhr.statusText // "OK"
🔹 Creating XMLHttpRequest
The first step in AJAX is creating an XMLHttpRequest object. This object provides methods and properties for server communication.
// Create new XMLHttpRequest object
const xhr = new XMLHttpRequest();
// Check if object was created successfully
if (xhr) {
console.log('XMLHttpRequest object created!');
}
// Alternative: Check browser support
if (window.XMLHttpRequest) {
const xhr = new XMLHttpRequest();
} else {
// For old IE browsers
const xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
Console Output:
XMLHttpRequest object created!
🔹 XMLHttpRequest Methods
XMLHttpRequest provides essential methods for configuring and sending requests to servers. These methods control the entire request lifecycle.
- open(method, url, async): Initialize a request
- send(): Send the request to server
- setRequestHeader(): Set HTTP request headers
- abort(): Cancel the current request
- getAllResponseHeaders(): Get all response headers
const xhr = new XMLHttpRequest();
// Initialize request
xhr.open('GET', 'data.txt', true);
// Set header
xhr.setRequestHeader('Content-Type', 'application/json');
// Send request
xhr.send();
🔹 ReadyState Values
The readyState property tracks request progress through five stages, from initialization to completion. Understanding these states helps manage asynchronous operations effectively.
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
console.log('ReadyState: ' + xhr.readyState);
if (xhr.readyState === 4 && xhr.status === 200) {
console.log('Request complete!');
}
};
xhr.open('GET', 'data.txt', true);
xhr.send();
ReadyState Values:
- 0 (UNSENT): Request not initialized
- 1 (OPENED): Server connection established
- 2 (HEADERS_RECEIVED): Request received
- 3 (LOADING): Processing request
- 4 (DONE): Request finished, response ready
🔹 Complete XMLHttpRequest Example
Here's a full example demonstrating XMLHttpRequest object creation, configuration, and response handling:
<!DOCTYPE html>
<html>
<body>
<h2>XMLHttpRequest Demo</h2>
<button onclick="loadData()">Get Data</button>
<div id="output"></div>
<script>
function loadData() {
// Create XMLHttpRequest object
const xhr = new XMLHttpRequest();
// Configure response handler
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById('output').innerHTML = xhr.responseText;
} else {
document.getElementById('output').innerHTML = 'Error: ' + xhr.status;
}
};
// Initialize and send request
xhr.open('GET', 'info.txt', true);
xhr.send();
}
</script>
</body>
</html>