XMLHttpRequest (XHR)
The introduction of XMLHttpRequest (XHR) in browsers in the mid 2000's was a huge win for the Web Platform. Let's see how it works.
- Introduction
- An example XHR request
- Additional open() parameters
- onreadystatechange
- Aborting an XHR request
- Comparison with jQuery
- Comparison with Fetch
- Cross Domain Requests
- Uploading files using XHR
Introduction
The introduction of XMLHttpRequest (XHR) in browsers in the mid 2000’s was a huge win for the Web Platform. Let’s see how it works.
Things that now look normal, back in the day, looked like they were coming from the future. I’m talking about GMail or Google Maps, for example, which were all based in great part on XHR.
XHR was invented at Microsoft in the nineties, and became a de-facto standard as all browsers implemented it in the 2002-2006 period. The W3C standardized XMLHttpRequest in 2006.
As it sometimes can happen in the Web Platform, initially there were a few inconsistencies that made working with XHR quite different cross-browser.
Libraries like jQuery got a boost of popularity by providing an easy to use abstraction for developers, and this in turn helped spread the usage of this technology.
An example XHR request
The following code creates an XMLHttpRequest (XHR) request object, and attaches a callback function that responds on the onreadystatechange
event.
The xhr connection is set up to perform a GET request to https://yoursite.com
, and it’s started with the send()
method:
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
In the example above we just passed the method and the URL to the request.
We can also specify the other HTTP methods - (get
, post
, head
, put
, delete
, options
).
Other parameters let you specify a flag to make the request synchronous if set to false, and a set of credentials for HTTP authentication:
open(method, url, asynchronous, username, password)
onreadystatechange
The onreadystatechange
is called multiple times during an XHR request. We explicitly ignore all the states other than readyState === 4
, which means that the request is 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
An XHR request can be aborted by calling the abort()
method on the xhr
object.
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 Domain Requests
Note that an XMLHttpRequest connection is subject to specific limits that are enforced for security reasons.
One of the most obvious is the enforcement of the same origin policy.
You cannot access resources on another server, unless the server explicitly supports this using CORS (Cross Origin Resource Sharing).
Uploading files using XHR
Check out my tutorial on how to upload files using XHR.
→ I wrote 17 books to help you become a better developer:
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025