Skip to content

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

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

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.


download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about platform: