XMLHttpRequest (XHR)

In the mid-2000s, the introduction of XMLHttpRequest (XHR) into the browser was a huge victory for the Web platform. Let us see how it works.

Introduction

In the mid-2000s, the introduction of XMLHttpRequest (XHR) into the browser was a huge victory for the Web platform. Let us see how it works.

From now on, things that seem normal now look like they come from the future. For example, I’m talking about GMail or Google Maps, both of which are largely based on XHR.

XHR was invented at Microsoft in the 1990s and became the de facto standard because all browsers implemented XHR between 2002 and 2006. W3C standardized XMLHttpRequest in 2006.

Since it can sometimes happen on the Web platform, there are some inconsistencies initially that make the cross-browser using XHR quite different.

Libraries like jQuery have gained widespread popularity by providing developers with easy-to-use abstractions, which in turn helped promote the use of the technology.

XHR request example

The following code creates an XMLHttpRequest (XHR) request object and attaches aonreadystatechangeevent.

The xhr connection is set to perform a GET request tohttps://yoursite.comAnd fromsend()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()

Other open() parameters

In the above example, we just passed the method and URL to the request.

We can also specify other HTTP methods-(get,post,head,put,delete,options).

Other parameters allow you to specify a flag (if set to false to synchronize the request), and a set of credentials for HTTP authentication:

open(method, url, asynchronous, username, password)

onreadystatechange

ThisonreadystatechangeIt is called multiple times during the XHR request. We explicitly ignore all states except the followingreadyState === 4, Which means the request has been completed.

These states are

  • 1 (opened): request to start
  • 2 (HEADERS_RECEIVED): HTTP headers have been received
  • 3 (loading): start downloading in response
  • 4 (Completed): The response has been downloaded

Aborting XHR request

The request can be aborted by calling the XHR requestabort()On the methodxhrpurpose.

Compare with jQuery

Using jQuery, these lines can be converted to:

$.get('https://yoursite.com', data => {
  console.log(data)
}).fail(err => {
  console.error(err)
})

Comparison with extraction

along withExtract APIThis is the equivalent code:

fetch('https://yoursite.com')
  .then(data => {
    console.log(data)
  })
  .catch(err => {
    console.error(err)
  })

Cross-domain request

Please note that for security reasons, XMLHttpRequest connections are subject to certain restrictions.

One of the most obvious examples is the implementation of the same source strategy.

You cannot access resources on other servers,unlessThe server explicitly supports this operation using the following commandCORS (Cross-Origin Resource Sharing).

Upload files using XHR

Check out my tutorialHow to upload files using XHR.

Download mine for freeJavaScript beginner's manual


More browser tutorials: