Skip to content
the poor coder

how to send json in js with post

Poor Man
Published
Reading time
2 min read
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.

Text

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.

Text

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.

Text

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!

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC