🌐 Modern Ajax Made Simple
XMLHttpRequest? 10 lines for simple GET? Callback hell? Fetch API is promise-based, clean syntax, built-in JSON parsing. Modern Ajax the right way.
❌ XMLHttpRequest (10+ lines)
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/users');
xhr.onload = function() {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
} else {
console.error('Request failed');
}
};
xhr.onerror = function() {
console.error('Network error');
};
xhr.send();
✅ Fetch API (Clean!)
// Promise syntax
fetch('https://api.example.com/users')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
// Or async/await (even cleaner!)
async function getUsers() {
try {
const response = await fetch('https://api.example.com/users');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
🎯 Common Patterns
// POST Request
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice', email: 'alice@example.com' })
});
// PUT/PATCH
await fetch('https://api.example.com/users/123', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Updated Name' })
});
// DELETE
await fetch('https://api.example.com/users/123', {
method: 'DELETE'
});
// With authentication token
await fetch('https://api.example.com/protected', {
headers: { 'Authorization': 'Bearer your-token-here' }
});
⚠️ Error Handling (Important!)
// IMPORTANT: Fetch only rejects on network error, not HTTP errors!
async function fetchWithErrorHandling() {
try {
const response = await fetch('https://api.example.com/users');
// Check if response is OK (status 200-299)
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Fetch error:', error);
throw error;
}
}
💡 Pro Tips
- Always check response.ok: Fetch doesn’t reject on 404, 500
- Use AbortController: For timeouts and request cancellation
- Cache responses: Use cache: ‘force-cache’ option
- CORS: Use mode: ‘cors’ for cross-origin requests
- Credentials: credentials: ‘include’ to send cookies
“Refactored entire codebase from XMLHttpRequest to Fetch. Code reduced by 40%. No more callback pyramids. Async/await made everything readable. Best decision for project health.”
