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
- XHR request example
- Other open() parameters
onreadystatechange
- Aborting XHR request
- Compare with jQuery
- Comparison with extraction
- Cross-domain request
- Upload files using XHR
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 aonreadystatechange
event.
The xhr connection is set to perform a GET request tohttps://yoursite.com
And 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
Thisonreadystatechange
It 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 methodxhr
purpose.
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:
- HTML5 provides some useful tips
- How do I make a CMS-based website work offline
- The complete guide to progressive web applications
- Extract API
- Push API guide
- Channel Messaging API
- Service staff tutorial
- Cache API guide
- Notification API guide
- Dive into IndexedDB
- Selectors API: querySelector and querySelectorAll
- Load JavaScript efficiently with delay and asynchrony
- Document Object Model (DOM)
- Web storage API: local storage and session storage
- Understand how HTTP cookies work
- History API
- WebP image format
- XMLHttpRequest (XHR)
- In-depth SVG tutorial
- What is the data URL
- Roadmap for learning network platforms
- CORS, cross-domain resource sharing
- Network worker
- requestAnimationFrame() guide
- What is Doctype
- Use DevTools console and console API
- Speech Synthesis API
- How to wait for DOM ready event in pure JavaScript
- How to add classes to DOM elements
- How to traverse DOM elements from querySelectorAll
- How to remove classes from DOM elements
- How to check if a DOM element has a class
- How to change the DOM node value
- How to add the click event to the list of DOM elements returned from querySelectorAll
- WebRTC, real-time Web API
- How to get the scroll position of an element in JavaScript
- How to replace DOM elements
- How to only accept images in the input file field
- Why use the preview version of the browser?
- Blob object
- File object
- FileReader object
- FileList object
- ArrayBuffer
- ArrayBufferView
- URL object
- Type array
- DataView object
- BroadcastChannel API
- Streams API
- FormData object
- Navigator object
- How to use the geolocation API
- How to use getUserMedia()
- How to use the drag and drop API
- How to scroll on a web page
- Processing the form in JavaScript
- Keyboard events
- Mouse event
- Touch event
- How to remove all children from DOM element
- How to create HTML attributes using raw Javascript
- How to check if the checkbox is checked using JavaScript?
- How to copy to clipboard using JavaScript
- How to disable buttons using JavaScript
- How to make a page editable in the browser
- How to use URLSearchParams to get query string value in JavaScript
- How to delete all CSS on the page at once
- How to use insertAdjacentHTML
- Safari, warning before exit
- How to add an image to the DOM using JavaScript
- How to reset the table
- How to use Google fonts