📡 XMLHttpRequest = Legacy AJAX
Before Fetch API, there was XMLHttpRequest. Still works, still used. Understand the foundation.
❌ XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/data');
xhr.onload = function() {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send();
✅ Fetch API (Modern)
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
🎯 XMLHttpRequest Examples
// GET request
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/users');
xhr.onload = function() {
if (xhr.status === 200) {
const users = JSON.parse(xhr.responseText);
console.log(users);
}
};
xhr.send();
// POST request
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/users');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 201) {
const newUser = JSON.parse(xhr.responseText);
console.log('Created:', newUser);
}
};
xhr.send(JSON.stringify({ name: 'Alice', email: 'alice@example.com' }));
// Error handling
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/users');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('Success:', xhr.responseText);
} else {
console.error('Error:', xhr.status);
}
};
xhr.onerror = function() {
console.error('Network error');
};
xhr.send();
// Progress tracking
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/large-file');
xhr.onprogress = function(event) {
if (event.lengthComputable) {
const percent = (event.loaded / event.total) * 100;
console.log(`Progress: ${percent}%`);
}
};
xhr.send();
💡 When to Use XHR
- Legacy browser support
- Progress tracking (upload/download)
- File uploads
- Binary data handling
- Abort requests
“XMLHttpRequest is the foundation. Fetch is modern, but XHR is still useful. Essential to understand.”
