XMLHttpRequest (XHR) is the classic API for making HTTP requests in JavaScript.
It provides detailed control over request/response handling with event-based progress tracking.
XMLHttpRequest API Reference
// Create request
const xhr = new XMLHttpRequest();
// Configure request
xhr.open('GET', 'https://api.example.com/data', true); // async=true
// Set headers
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('X-Custom-Header', 'value');
// Event handlers
xhr.onreadystatechange = () => {
// 0=UNSENT, 1=OPENED, 2=HEADERS_RECEIVED, 3=LOADING, 4=DONE
console.log('Ready state:', xhr.readyState);
};
xhr.onload = () => console.log('Load complete');
xhr.onerror = () => console.log('Network error');
xhr.onprogress = (e) => console.log(`Progress: ${e.loaded}/${e.total}`);
xhr.onabort = () => console.log('Request aborted');
xhr.ontimeout = () => console.log('Request timed out');
// Response properties
xhr.status // HTTP status code (200, 404, etc.)
xhr.statusText // Status text ("OK", "Not Found", etc.)
xhr.responseText // Response as text
xhr.responseXML // Response as XML document
xhr.response // Response based on responseType
xhr.responseType // '', 'arraybuffer', 'blob', 'document', 'json', 'text'
// Send request
xhr.send(); // GET/DELETE
xhr.send('data'); // POST/PUT with string
xhr.send(new FormData(formElement)); // POST with form data
xhr.send(JSON.stringify({key: 'value'})); // POST with JSON
// Abort request
xhr.abort();