Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
Introduction
XMLHttpRequest (XHR) was introduced in browsers in the mid-2000s and became a key part of the Web Platform. Gmail and Google Maps, for example, relied heavily on XHR for dynamic updates.
XHR was created at Microsoft in the 1990s and became a de facto standard as browsers implemented it (2002–2006). The W3C standardized it in 2006. Initially, browser support varied and libraries like jQuery became popular by abstracting XHR for developers.
Example XHR request
Create an XHR, listen for readystatechange, then call open() and send():
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
xhr.status === 200 ? console.log(xhr.responseText) : console.error('error')
}
}
xhr.open('GET', 'https://yoursite.com')
xhr.send()
Additional open() parameters
You can use other HTTP methods (GET, POST, HEAD, PUT, DELETE, OPTIONS). Additional parameters: async (false for synchronous), and optional username and password for HTTP authentication:
open(method, url, asynchronous, username, password)
onreadystatechange
onreadystatechange fires multiple times during a request. Typically you only handle readyState === 4 (DONE).
The states are:
- 1 (OPENED): the request starts
- 2 (HEADERS_RECEIVED): the HTTP headers have been received
- 3 (LOADING): the response begins to download
- 4 (DONE): the response has been downloaded
Aborting an XHR request
Call xhr.abort() to abort the request.
Comparison with jQuery
With jQuery these lines can be translated to:
$.get('https://yoursite.com', (data) => {
console.log(data)
}).fail((err) => {
console.error(err)
})
Comparison with Fetch
With the Fetch API this is the equivalent code:
fetch('https://yoursite.com')
.then((data) => {
console.log(data)
})
.catch((err) => {
console.error(err)
})
Cross-origin requests
XHR is subject to the same-origin policy. Cross-origin requests require the server to support CORS.
Uploading files with XHR
See how to upload files with XHR.
Lessons in this unit:
| 0: | Introduction |
| 1: | The Fetch API |
| 2: | ▶︎ XMLHttpRequest |
| 3: | CORS |
| 4: | Streams API |