To use XHR, you need to be able to do two things:
- Send a request with XHR
- Receive a response with XHR
Sending a request
There are three steps to send a request with XHR:
- Create an
XMLHttpRequestobject - Create a request with the
openmethod. - Send the request with a
sendmethod.
First, you create a new XMLHttpRequest object:
const request = new XMLHttpRequest()Second, you open a request with the open method. Here, you need to pass in an HTTP method and a url (the endpoint) to the API.
We’ll talk about HTTP methods and endpoints in a later lesson. For now, here’s what this would look like:
request.open('GET', 'https://link-to-resource')Next, you have to send the request using the send method.
request.send()Together, the sending process looks like this:
const request = new XMLHttpRequest()request.open('GET', 'https://link-to-resource')request.send()Receiving a response
To receive a response, you have to use an event listener that listens for the load event.
request.addEventListener('load', event => { // Do something with the response})Data that comes back from the response can be found in event.target.
- If you
console.logthis andevent.target, you will find aresponseproperty. - This
responseproperty contains the data. - This
datais called thepayload.
For example, you can use the following request to get a list of my repositories on GitHub.
const request = new XMLHttpRequest()request.open('get', 'https://api.github.com/users/zellwk/repos')request.send()
request.addEventListener('load', event => { console.log(event.target)})
In this case, GitHub sends us a JSON value in the response property.
We need to convert this value into JavaScript before we can use it.
We can do this with JSON.parse
request.addEventListener('load', event => { const { response } = event.target const payload = JSON.parse(response) console.log(repos)})
JSON is one of the most important concepts you need to know to use Rest APIs today. We’ll cover what it is and how to convert from JavaScript to JSON and back in a later lesson.
Wrapping Up
Here’s the full code you need to fetch a resource with XHR.
const request = new XMLHttpRequest()request.open('get', 'https://api.github.com/users/zellwk/repos')request.send()
request.addEventListener('load', event => { const { response } = event.target const payload = JSON.parse(response) // Do something with the payload})As you can see, you have to write a lot of stuff! This is why XHR is not developer friendly and many people chose to use Fetch over XHR.
Now let’s move on and learn about the Fetch API.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson