AJAX XMLHttp
Understanding the XMLHttpRequest Object
🔧 What is XMLHttpRequest?
XMLHttpRequest is the JavaScript object that makes AJAX possible. It's like a messenger that carries data between your webpage and the server!
// Creating an XMLHttpRequest object
const xhr = new XMLHttpRequest();
// This object can:
// - Send requests to server
// - Receive responses
// - Handle different data types
// - Work asynchronously
XMLHttpRequest is your:
📮 Postal service to the server
📞 Phone line for communication
🚚 Delivery truck for data
XMLHttpRequest Features
Create Object
Make a new XMLHttpRequest instance
const xhr = new XMLHttpRequest();
Configure Request
Set up where and how to send
xhr.open('GET', 'data.json', true);
Send Request
Actually send the request
xhr.send(); // or xhr.send(data)
Handle Response
Process the server's reply
xhr.onload = function() { ... }
🔹 Creating XMLHttpRequest
Always start by creating a new XMLHttpRequest object:
// Method 1: Simple creation
const xhr = new XMLHttpRequest();
// Method 2: With error handling
let xhr;
try {
xhr = new XMLHttpRequest();
console.log('XMLHttpRequest created successfully!');
} catch (error) {
console.log('Error creating XMLHttpRequest:', error);
}
// Method 3: Check if supported
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest(); // Modern browsers
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP'); // Old IE
}
Result:
✅ XMLHttpRequest object ready to use
✅ Can now configure and send requests
🔹 XMLHttpRequest Properties
Important properties you'll use frequently:
const xhr = new XMLHttpRequest();
// Status properties
console.log(xhr.readyState); // 0-4 (request state)
console.log(xhr.status); // HTTP status code (200, 404, etc.)
console.log(xhr.statusText); // Status message ('OK', 'Not Found')
// Response properties
console.log(xhr.responseText); // Response as text
console.log(xhr.responseXML); // Response as XML document
console.log(xhr.response); // Response in specified format
// Request properties
console.log(xhr.timeout); // Timeout in milliseconds
📊 ReadyState Values:
- 0 (UNSENT): Request not initialized
- 1 (OPENED): Connection established
- 2 (HEADERS_RECEIVED): Request received
- 3 (LOADING): Processing request
- 4 (DONE): Request finished and response ready
🔹 XMLHttpRequest Methods
Essential methods for making requests:
const xhr = new XMLHttpRequest();
// 1. open() - Configure the request
xhr.open(method, url, async, user, password);
// Examples:
xhr.open('GET', 'data.txt', true);
xhr.open('POST', 'submit.php', true);
// 2. send() - Send the request
xhr.send(); // For GET requests
xhr.send(data); // For POST requests
// 3. setRequestHeader() - Set HTTP headers
xhr.setRequestHeader('Content-Type', 'application/json');
// 4. abort() - Cancel the request
xhr.abort();
// 5. getResponseHeader() - Get response header
const contentType = xhr.getResponseHeader('Content-Type');
🔹 Complete XMLHttpRequest Example
Here's a full example showing all the pieces together:
function makeRequest() {
// 1. Create XMLHttpRequest object
const xhr = new XMLHttpRequest();
// 2. Configure request
xhr.open('GET', 'user-data.json', true);
// 3. Set up event handlers
xhr.onreadystatechange = function() {
console.log('ReadyState:', xhr.readyState);
if (xhr.readyState === 4) { // Request complete
if (xhr.status === 200) { // Success
console.log('Success!');
document.getElementById('result').innerHTML = xhr.responseText;
} else { // Error
console.log('Error:', xhr.status, xhr.statusText);
document.getElementById('result').innerHTML = 'Error loading data';
}
}
};
// 4. Handle loading state
xhr.onload = function() {
console.log('Request completed');
};
// 5. Handle errors
xhr.onerror = function() {
console.log('Network error occurred');
};
// 6. Send the request
xhr.send();
}
Interactive Demo:
🔹 Modern Alternative: Fetch API
While XMLHttpRequest is still widely used, modern JavaScript also has the Fetch API:
XMLHttpRequest vs Fetch:
XMLHttpRequest:
- ✅ Supported everywhere
- ✅ More control over request
- ❌ More verbose code
- ❌ Callback-based
Fetch API:
- ✅ Cleaner syntax
- ✅ Promise-based
- ❌ Not in older browsers
- ❌ Less control
// Same request with both methods:
// XMLHttpRequest way:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'data.json', true);
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
// Fetch API way:
fetch('data.json')
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));