Introduction:
XMLHttpRequest() is a crucial tool in web development, empowering your web applications to interact with servers and retrieve data without having to refresh the page.
In this article, We'll understand what is XMLHttpRequest,how it works, how to use it and many more!
So,Without delaying further,let's START!
What is XMLHttpRequest?
In JavaScript, the XMLHttpRequest
method is used to make asynchronous requests to the server and load the information that is returned by the server onto the web pages.
XMLHttpRequest is mainly used in AJAX programming. With this method, we can update the parts of the web page without reloading the whole webpage.
Now, There's a much more optimized way to send request
to the server using fetch
method.
How it Works?
When we use the XHR method, It creates
XMLHttpRequest Object
A callback function
With the XMLHttpRequest
object, we can send a request to the server using the open()
and send()
methods respectively, and get data from the server.
State Management:
Unlike the fetch
method, XHR monitors the API requests by exposing states. These Different states are represented by integer values. And we can check the values using readystate
property.
Here are the different states of an XHR:
Value | State | Description |
0 | UNSENT | Client has been created. open() not called yet. |
1 | OPENED | open() has been called. |
2 | HEADERS_RECEIVED | send() has been called, and headers and status are available. |
3 | LOADING | Downloading; responseText holds partial data. |
4 | DONE | The operation is complete. |
For more details check MDN Docs.
XMLHttpRequest
object travels them in the order 0
→ 1
→ 2
→ 3
→ … → 3
→ 4
. State 3
repeats every time a data packet is received over the network.How to use XMLHttpRequest?
Now you have the basic idea of XHR and How it works. So Let's understand how to use XHR to get data from the server.
In this part, we'll be sending a request to the Github server and getting one user's details.
So, Without delaying further, Let's Start!
1. At first, we'll create an XHR object.
const xhr = new XMLHttpRequest();
2. After creating the object, We'll now send a request to the server.
xhr.open('GET', 'https://api.github.com/users/Arindam200'
);
const requestUrl = 'https://api.github.com/users/Arindam200'
xhr.open('GET', requestURL);
But the request Hasn't been sent yet! Because the open method can't call itself.
3. To send the Request, we need to call the open Method.
xhr.send()
This method opens the connection and sends the request to the server.
Note: We can also pass the request body through the optional body parameter.
xhr.send([body])
Some request methods like
GET
does not have a body. And some of them likePOST
usebody
to send the data to the server4.
We can terminate the request at any time. The call to xhr.abort()
does that:
xhr.abort(); // terminate the request
That triggers abort
event, and xhr.status
becomes 0
.
4. Now, Let's track the State and How they are changing. For that, We have to create one Call back function.
xhr.onreadystatechange = function() {
console.log(xhr.readyState)
}
After executing this, We'll get the following.
This callback function executes every time the state is changing.
5. Now, Let's see the response we are getting. We'll get the Response when the state change completes, which means the readyState
is 4.
xhr.onreadystatechange = function(){
console.log(xhr.readyState);
if (xhr.readyState === 4) {
console.log(responseText);
}
}
Let's see the console now.
Okay! So we got an error here!
Can you guess why?
Simply because We haven't referenced it properly. In our code snippet, we're logging responseText
without specifying where it comes from.
To fix this error, We have to provide the correct context of the variable. So the Correct code will be:
xhr.onreadystatechange = function(){
console.log(xhr.readyState);
if (xhr.readyState === 4) {
console.log(this.responseText);
}
}
After Defining the Correct context, we'll get the desired response! It'll look like this:
6. Now, we'll store the response in a variable and access its property! As an example, I'm Accessing the name
property.
xhr.onreadystatechange = function(){
console.log(xhr.readyState);
if (xhr.readyState === 4) {
const data = this.responseText
console.log(data.name);
}
}
Let's see the Output:
Wait! We have done everything right! But why we can't access the name property?
Here's the catch!
The response we are getting is of type String
, not Object
. Let's ensure this let's check the type of the function:
console.log(typeof data);
And we got:
7. For the above-mentioned reason, We aren't able to access the properties.
But How to fix this?
To fix this, We have to convert the string into JSON
data!
const data = JSON.parse(this.responseText)
Now If we check the type of data, We will get as Object
.
And with that, we can access the desired properties!
8. Here's the complete Code:
const requestUrl = "https://api.github.com/users/Arindam200";
const xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl);
xhr.onreadystatechange = function () {
console.log(xhr.readyState);
if (xhr.readyState === 4) {
const data = JSON.parse(this.responseText);
console.log(typeof data);
console.log(data.name);
}
};
xhr.send();
Conclusion
If you found this blog post helpful, please consider sharing it with others who might benefit. You can also follow me for more content on Javascript, React, and other web Development topics.
For Paid collaboration mail me at : arindammajumder2020@gmail.com
Connect with me on Twitter, LinkedIn, Youtube and GitHub.
Thank you for Reading :)