In JavaScript, you can use the XMLHttpRequest
object to send HTTP requests, including POST requests, to a server. Here’s an example of how to make a POST request using XMLHttpRequest
:
var xhr = new XMLHttpRequest();
var url = "http://example.com/api";
var params = "param1=value1¶m2=value2"; // POST parameters
xhr.open("POST", url, true);
// Set the content type header, if needed
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Request completed successfully
var response = xhr.responseText;
console.log(response);
}
};
xhr.send(params);
Use the send()
method to send the request. If you need to send data in the request body, pass it as an argument to the send()
method (data
in this example). The data can be in various formats, such as a string, a FormData object, or a JSON string.
JavaScript XMLHttpRequest POST example
Simple example code how to make a POST request using the XMLHttpRequest object in JavaScript.
1. Create a new XMLHttpRequest object:
var xhr = new XMLHttpRequest();
2. Define the URL to which the POST request will be sent:
var url = "https://jsonplaceholder.typicode.com/posts";
3. Prepare the data to be sent in the request payload.
In this example, the data is an object that is converted to a JSON string using JSON.stringify()
:
var data = JSON.stringify({ title: "Post Title", body: "Post Body", userId: 1 });
4. Open the connection:
By specifying the HTTP method (“POST”), the URL, and whether to make the request asynchronously (true
in this case):
xhr.open("POST", url, true);
5. Set the request header to specify the content type as JSON:
xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
6. Define a callback function:
To handle the response when the readyState of the XMLHttpRequest object changes:
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 201) {
var response = JSON.parse(xhr.responseText);
console.log(response);
} else {
console.log("Error:", xhr.status);
}
}
};
7. Send the POST request with the data as the request payload:
xhr.send(data);
Complete code
var xhr = new XMLHttpRequest();
var url = "https://jsonplaceholder.typicode.com/posts";
var data = JSON.stringify({ title: "Post Title", body: "Post Body", userId: 1 }); // Request payload
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 201) {
var response = JSON.parse(xhr.responseText);
console.log(response);
} else {
console.log("Error:", xhr.status);
}
}
};
xhr.send(data);
Output:
When the response is received, the onreadystatechange
callback function is triggered. If the readyState is XMLHttpRequest.DONE
(4) and the status is 201
(indicating a successful request), the response text is parsed into a JSON object and logged to the console. If there is an error, the status code is logged to the console.
Comment if you have any doubts or suggestions on this Js Async topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version