The JavaScript XMLHttpRequest object is a built-in feature that allows for making asynchronous HTTP requests in web applications. It provides a way to communicate with servers, retrieve data, and handle server responses without the need for page reloading.
The syntax for creating an XMLHttpRequest object and using its methods and properties in JavaScript is as follows:
1. Create an instance of the XMLHttpRequest object:
var xhr = new XMLHttpRequest();
2. Open a connection to the server using the open()
method:
xhr.open(method, url, async);
method
: The HTTP method to be used for the request (e.g., “GET”, “POST”, “PUT”, “DELETE”).url
: The URL of the server endpoint.async
(optional): A Boolean value indicating whether the request should be asynchronous or not. By default, it’s set totrue
.
3. Set optional request headers using the setRequestHeader()
method:
xhr.setRequestHeader(header, value);
4. Set a callback function to handle the response using the onreadystatechange
event handler:
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// Handle the response here
}
};
5. Send the request to the server using the send()
method:
xhr.send(data);
data
(optional): The data to be sent with the request, typically used with POST or PUT requests.
6. Retrieve the response data from the server:
The response data can be accessed through the responseText
property, which contains the response as a string.
var response = xhr.responseText;
Alternatively, you can use the responseXML
property if the response is expected to be XML.
var response = xhr.responseXML;
You can also access the HTTP status code of the response using the status
property.
var status = xhr.status;
To retrieve the response headers, you can use the getAllResponseHeaders()
method, which returns a string containing all the response headers.
var headers = xhr.getAllResponseHeaders();
Note: to handle errors and other possible states of the XMLHttpRequest object for a more robust implementation.
JavaScript XMLHttpRequest example
Simple example code of how to use XMLHttpRequest to make an HTTP GET request and retrieve data from a server:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send();
Output:
XMLHttpRequest Object Methods
The XMLHttpRequest object provides several methods to interact with the server and manage the HTTP request. Here are some commonly used methods:
Method | Description |
---|---|
open(method, url, async) | Initializes a request and specifies the HTTP method, URL, and whether the request should be asynchronous. |
setRequestHeader(header, value) | Sets the value of an HTTP request header before sending the request. |
send(data) | Sends the HTTP request to the server. Can include optional data for POST or PUT requests. |
abort() | Aborts the current request, canceling it before it completes. |
getResponseHeader(header) | Returns the value of the specified response header from the server’s response. |
getAllResponseHeaders() | Returns all the response headers from the server’s response as a single string. |
XMLHttpRequest Object Properties
The XMLHttpRequest object provides various properties that allow you to access information related to the HTTP request and response. Here are some commonly used properties:
Property | Description |
---|---|
readyState | Represents the state of the XMLHttpRequest object. |
status | Holds the status code of the HTTP response (e.g., 200 for success). |
statusText | Returns the status message corresponding to the status code. |
responseType | Determines the type of response expected from the server. |
responseText | Returns the response body as a string. |
responseXML | Returns the response body as an XML document. |
timeout | Sets or retrieves the timeout value for the request. |
withCredentials | Indicates whether the request should include credentials such as cookies when sending the request. |
Here’s an example that demonstrates how to use the different HTTP methods (GET, POST, PUT, DELETE) with the XMLHttpRequest object:
GET Request:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send();
POST Request:
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://api.example.com/data", true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = {
name: "John",
age: 25
};
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 201) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send(JSON.stringify(data));
PUT Request:
var xhr = new XMLHttpRequest();
xhr.open("PUT", "https://api.example.com/data/123", true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = {
name: "John",
age: 26
};
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send(JSON.stringify(data));
DELETE Request:
var xhr = new XMLHttpRequest();
xhr.open("DELETE", "https://api.example.com/data/123", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 204) {
console.log("Resource deleted successfully.");
}
};
xhr.send();
Adjust the URLs and payload data as per your specific requirements and server configuration.
Do comment if you have any doubts or suggestions on this Js code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version