JavaScript Event Handler
Listens for user interactions
↓
2
⚙️ Create XMLHttpRequest Object
JavaScript creates an XMLHttpRequest object to handle the request
// Create XMLHttpRequest object
const xhr = new XMLHttpRequest();
// Alternative: For older browsers
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
// Code for IE6, IE5
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
Browser creates XHR Object
Object initialized readyState = 0
↓
3
🔧 Configure the Request
Set up the request method, URL, and async flag
// Configure the request
xhr.open('GET', 'https://api.example.com/data', true);
// Parameters:
// 1. Method: GET, POST, PUT, DELETE
// 2. URL: API endpoint
// 3. Async: true (asynchronous) or false (synchronous)
open() called
readyState = 1
Request Method Set
GET, POST, etc.
URL Configured
API endpoint
↓
4
🎯 Set Up Event Handlers
Define what happens when request state changes and when response arrives
// Set up onreadystatechange handler
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// Success - process response
processResponse(xhr.responseText);
} else {
// Error handling
handleError(xhr.status);
}
}
};
// Modern approach with onload/onerror
xhr.onload = function() {
if (xhr.status === 200) {
processResponse(xhr.response);
}
};
xhr.onerror = function() {
handleError('Network error');
};
↓
5
📤 Send the Request
The request is sent to the server asynchronously
// Send the request
xhr.send();
// For POST requests with data
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({ key: 'value' }));
Browser
Sends HTTP Request
Request Sent
readyState = 2
Headers received
Request In Flight🚀 → → → →Server Processing
Web Server
Receives & Processes Request
↓
6
🔄 Server Processes Request
Server receives request, processes it, and prepares response
// Server-side example (Node.js/Express)
app.get('/api/data', (req, res) => {
// Process request
const data = fetchFromDatabase();
// Send response
res.json({
status: 'success',
data: data,
timestamp: new Date()
});
});
Receive HTTP Request
Process Request
Generate Response
Send Response
↓
7
📥 Browser Receives Response
Browser receives response in chunks (readyState = 3) then complete (readyState = 4)