XMLHttpRequest
XMLHttpRequest (XHR) is a browser API that allows JavaScript to make HTTP requests to servers. While largely superseded by the modern Fetch API, XHR is still used in legacy code and some libraries.
Basic Usage
javascriptconst xhr = new XMLHttpRequest() xhr.open('GET', 'https://api.example.com/data') xhr.onload = function() { if (xhr.status === 200) { const data = JSON.parse(xhr.responseText) console.log(data) } } xhr.onerror = function() { console.error('Request failed') } xhr.send()
POST Request
javascriptconst xhr = new XMLHttpRequest() xhr.open('POST', '/api/users') xhr.setRequestHeader('Content-Type', 'application/json') xhr.onload = function() { console.log('Response:', xhr.responseText) } const data = JSON.stringify({ name: 'Alice', age: 30 }) xhr.send(data)
Event Handlers
javascriptxhr.onloadstart = () => console.log('Request started') xhr.onprogress = (e) => console.log(`Progress: ${e.loaded}/${e.total}`) xhr.onload = () => console.log('Request complete') xhr.onerror = () => console.error('Request error') xhr.onabort = () => console.log('Request aborted') xhr.ontimeout = () => console.error('Request timeout')
Properties
javascriptxhr.status // HTTP status code (200, 404, etc.) xhr.statusText // Status message xhr.responseText // Response as text xhr.responseXML // Response as XML document xhr.readyState // Current state (0-4)
Modern Alternative: Fetch
javascript// XHR (old way) const xhr = new XMLHttpRequest() xhr.open('GET', '/api/data') xhr.onload = () => console.log(xhr.responseText) xhr.send() // Fetch (modern way) fetch('/api/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)) // Async/await const response = await fetch('/api/data') const data = await response.json()
Why Fetch is Preferred
- Promise-based (cleaner async code)
- Simpler API
- Better error handling
- Works with modern JavaScript features
- More consistent across browsers
When XHR is Still Used
- Legacy codebases
- Libraries like Axios (built on XHR)
- Need for upload progress tracking
- Specific browser compatibility needs