XHR, also known as or AJAX, is one of the things that gave birth to the “modern” Web.
Its introduction led to the possibility to create apps inside the browser, where before you only had documents and applications that required a complete back-and-forth to the server to get an entirely new page.
Today we take things for granted, but I remember at the time it looked like magic. I’m thinking about GMail or Google Maps, for example. Clicking a link does not cause a page refresh to get some data from the servers. It all works more like in a “desktop” application.
The W3C standardized XMLHttpRequest in 2006. As it sometimes happen in the Web Platform, initially there were a few inconsistencies that made working with XHR quite different cross-browser, but today the standard is rock solid, and it’s based on the XMLHttpRequest
object.
The following code creates an XMLHttpRequest
request object, then we attach 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()
Some more details on onreadystatechange
See how we check for the readyState
property to be 4
? That magic number means the request is done.
The other states we can check for 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
Cross Domain Requests
Note that an XMLHttpRequest connection is subject to CORS, enforced for security reasons.
You cannot access resources on another server, unless the server explicitly supports this using CORS, which we introduced in the previous lesson.