how to send json in js with post
- Published
- Reading time
- 2 min read
- Length
- 252 words
On this page
How to send JSON in JS with POST Method#
If you want to send JSON data using JavaScript, you can do that using the POST method. There are multiple ways to do so, and here are some of them:
Using XMLHttpRequest#
You can use the XMLHttpRequest object to send JSON data. This method is widely used and supported by all modern browsers.
const xhr = new XMLHttpRequest();
const url = "your-url-here";
const data = JSON.stringify({
name: "John",
age: 30
});
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.onload = function () {
const response = JSON.parse(xhr.responseText);
console.log(response);
};
xhr.send(data);Using Fetch API#
The Fetch API is a newer and more elegant way to send JSON data using JavaScript. It is supported by most modern browsers.
const url = "your-url-here";
const data = JSON.stringify({
name: "John",
age: 30
});
fetch(url, {
method: "POST",
headers: {
"Content-type": "application/json; charset=utf-8"
},
body: data
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));Using jQuery#
If you are already using jQuery in your project, you can use its ajax() method to send JSON data using JavaScript.
const url = "your-url-here";
const data = JSON.stringify({
name: "John",
age: 30
});
$.ajax({
type: "POST",
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response);
},
error: function (error) {
console.error(error);
}
});These are some of the ways to send JSON data using JavaScript. You can choose the one that suits you the best. Hope this helps!