XMLHttpRequest (XHR) is an API that is used to send and receive HTTP or HTTPS requests in JavaScript. It is widely used for building web applications that interact with web servers asynchronously.
In this post, we will explain how to send a request using XMLHttpRequest in JavaScript.
1. Creating an XMLHttpRequest object
To send a request using XMLHttpRequest, you need to create an instance of the XMLHttpRequest object. You can create an instance of the object as follows:
const xhr = new XMLHttpRequest();
2. Configuring the request
After creating the object, you need to configure the request by setting the HTTP method, URL, and other options. You can set the method using the open()
method of the XMLHttpRequest object, as shown below:
xhr.open("GET", "https://example.com/api/users", true);
In the above code, we set the HTTP method to GET
and the URL to https://example.com/api/users
. The third parameter of the open()
method specifies whether the request should be asynchronous or not. A value of true
indicates an asynchronous request.
3. Sending the request
After configuring the request, you can send it using the send()
method of the XMLHttpRequest object, as shown below:
xhr.send();
In the above code, we send the request without any data.
4. Handling the response
Once the request is sent, you need to handle the response. You can handle the response using the onreadystatechange event of the XMLHttpRequest object, as shown below:
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
}
};
In the above code, we set a function to be called whenever the readyState
property of the XMLHttpRequest
object changes. The function checks if the readyState
is equal to 4, which means the request has completed, and the status
is equal to 200, which means the response was successful. If the conditions are met, the function logs the response text to the console.
Putting it all together
Putting all the above code together, we have the following:
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://example.com/api/users", true);
xhr.send();
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
}
};
In the above code, we create an instance of the XMLHttpRequest object, set the HTTP method to GET
, and the URL to https://example.com/api/users
. We then send the request and set a function to be called when the response is received. The function checks if the response was successful and logs the response text to the console.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.