XMLHttpRequest: The Classic AJAX API
XMLHttpRequest is the original browser API for asynchronous HTTP requests. Fetch is usually the better default for new code, but XMLHttpRequest remains useful in older applications and for features such as upload progress events.
Send a GET request
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/status.php');
xhr.responseType = 'json';
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.response);
} else {
console.error(`Request failed: ${xhr.status}`);
}
};
xhr.onerror = () => console.error('Network error');
xhr.send();
Key events and properties
load runs when a response has completed, error indicates a network-level failure, and timeout can handle a configured timeout. Check status before treating a response as successful.
When maintaining legacy code
Keep callbacks small, centralize response parsing, and ensure every request has success and failure handling. Avoid synchronous XHR on the main thread because it can freeze the interface. For new code, consider Fetch and AbortController.