XMLHttpRequest Overview
XMLHttpRequest provides a JavaScript API for making HTTP requests directly from the browser. It enables dynamic page updates without full page reloads, allowing applications to exchange data with servers in the background.
Request Lifecycle
Sending GET Requests
// Create a new XHR instance
const request = new XMLHttpRequest();
// Initialize the request with method, URL, and async flag
request.open('GET', 'http://127.0.0.1:8080/data?key1=val1&key2=val2');
// Send the request to the server
request.send();
// Listen for state changes to handle the response
request.onreadystatechange = () => {
// readyState values: 0=uninitialized, 1=opened, 2=headers_received,
// 3=loading, 4=done
if (request.readyState === 4 && request.status === 200) {
console.log(request.status); // HTTP status code (e.g., 200)
console.log(request.statusText); // Status text (e.g., "OK")
console.log(request.getAllResponseHeaders());
console.log(request.response); // Response body
console.log(request.responseType); // Response type
}
};
Sending POST Requests
const req = new XMLHttpRequest();
req.open('POST', 'http://127.0.0.1:8080/submit');
// Set Content-Type header before sending
req.setRequestHeader('Content-Type', 'application/json');
// Send JSON data
req.send(JSON.stringify({ key1: 'val1', key2: 'val2' }));
req.onreadystatechange = () => {
if (req.readyState === 4 && req.status === 200) {
const data = JSON.parse(req.response);
console.log(data);
}
};
Canceling Requests
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1:8080/data');
xhr.send();
// Abort the request and reset readyState to 0
xhr.abort();
Timeout and Error Handling
Configuring Request Timeout
const httpReq = new XMLHttpRequest();
// Set maximum request duration in milliseconds
httpReq.timeout = 3000;
httpReq.ontimeout = () => {
alert('Request timed out');
};
httpReq.open('GET', 'http://127.0.0.1:8080/data');
httpReq.send();
httpReq.onreadystatechange = () => {
if (httpReq.readyState === 4 && httpReq.status === 200) {
console.log(httpReq.response);
}
};
Handling Network Errors
const client = new XMLHttpRequest();
client.onerror = () => {
alert('Network error occurred');
};
client.open('GET', 'http://127.0.0.1:8080/data');
client.send();
client.onreadystatechange = () => {
if (client.readyState === 4 && client.status === 200) {
console.log(client.response);
}
};
API Reference
Properties
| Property |
Access |
Description |
| readyState |
read-only |
Current state: 0 (uninitialized), 1 (opened), 2 (headers received), 3 (loading), 4 (done) |
| status |
read-only |
HTTP status code (200, 404, 500, etc.) |
| statusText |
read-only |
HTTP status message ("OK", "Not Found", etc.) |
| response |
read-only |
Response body content |
| responseType |
configurable |
Expected response type: "", "text", "arraybuffer", "blob", "document", "json" |
| timeout |
configurable |
Maximum request duration in milliseconds |
Events
| Event |
Trigger |
| onreadystatechange |
Fired when readyState changes |
| ontimeout |
Fired when timeout threshold is exceeded |
| onerror |
Fired when a network error occurs |
Methods
| Method |
Description |
| open(method, url, async) |
Initialize request. method: GET/POST/PUT/DELETE, async default true |
| setRequestHeader(name, value) |
Set request header, must be callled between open() and send() |
| send(body) |
Transmit the request. body optional for GET requests |
| abort() |
Cancel the current request, resets readyState to 0 |
| getAllResponseHeaders() |
Returns all response headers as a string |