Sending and receiving data in JSON format using POST method

// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
var data = JSON.stringify({"email": "[email protected]", "password": "101010"});
xhr.send(data);

Sending and receiving data in JSON format using GET method

// Sending a receiving data in JSON format using GET method
//      
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "[email protected]", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
xhr.send();

Handling data in JSON format on the server-side using PHP

<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>

The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.

Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE instead of xhr.readyState === 4 The problem is that Internet Explorer uses different state names so it's better to use state values.

Answer from hex494D49 on Stack Overflow
🌐
JSON Editor Online
jsoneditoronline.org › home › data-fetching › post-json
How to POST JSON data in JavaScript | Indepth | JSON Editor Online
February 8, 2023 - In node.js you can also use libraries like Axios, and you can use the node-fetch library, which has the same API as JavaScript’s fetch API in the browser. ... It can be that your HTTP request does not work at first. Let us go over some of the most common causes for your HTTP request not to work. When posting data using the plain JavaScript fetch function, it is easy to forget to serialize the body:
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Request › json
Request: json() method - Web APIs | MDN
November 7, 2025 - The request body cannot be parsed as JSON. js · const obj = { hello: "world" }; const request = new Request("/myEndpoint", { method: "POST", body: JSON.stringify(obj), }); request.json().then((data) => { // do something with the data sent in the request }); Response.json() Was this page helpful to you?
Top answer
1 of 2
290

Sending and receiving data in JSON format using POST method

// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
var data = JSON.stringify({"email": "[email protected]", "password": "101010"});
xhr.send(data);

Sending and receiving data in JSON format using GET method

// Sending a receiving data in JSON format using GET method
//      
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "[email protected]", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
xhr.send();

Handling data in JSON format on the server-side using PHP

<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>

The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.

Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE instead of xhr.readyState === 4 The problem is that Internet Explorer uses different state names so it's better to use state values.

2 of 2
29

Using new api fetch:

const dataToSend = JSON.stringify({"email": "[email protected]", "password": "101010"});
let dataReceived = ""; 
fetch("", {
    credentials: "same-origin",
    mode: "same-origin",
    method: "post",
    headers: { "Content-Type": "application/json" },
    body: dataToSend
})
    .then(resp => {
        if (resp.status === 200) {
            return resp.json()
        } else {
            console.log("Status: " + resp.status)
            return Promise.reject("server")
        }
    })
    .then(dataJson => {
        dataReceived = JSON.parse(dataJson)
    })
    .catch(err => {
        if (err === "server") return
        console.log(err)
    })

console.log(`Received: ${dataReceived}`)                
You need to handle when server sends other status rather than 200(ok), you should reject that result because if you were to left it in blank, it will try to parse the json but there isn't, so it will throw an error

🌐
ReqBin
reqbin.com › code › javascript › wzp2hxwh › javascript-post-request-example
How do I send a POST request using JavaScript?
To post data in JSON format using JavaScript/jQuery, you need to stringify your JavaScript object using the JSON.stringify() method and provide a Content-Type: application/json header with your request.
🌐
Stack Abuse
stackabuse.com › bytes › using-fetch-api-to-post-json-data-in-javascript
Using Fetch API to POST JSON Data in JavaScript
September 12, 2023 - The fetch() call returns a Promise ... the body text as JSON. To send a POST request with JSON data using Fetch, we need to pass an options object as the second argument to fetch()....
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Fetch_API › Using_Fetch
Using the Fetch API - Web APIs | MDN
js · const response = await fetch("https://example.org/post", { method: "POST", body: JSON.stringify({ username: "example" }), // … }); You can supply the body as an instance of any of the following types: a string · ArrayBuffer · TypedArray · DataView · Blob ·
🌐
Medium
medium.com › @kirstyn.nichole › creating-a-form-json-post-request-in-javascript-with-react-bad63a5e45bc
Creating a Form/JSON POST Request in JavaScript with React | by Kirstyn Canull | Medium
March 5, 2024 - In this example, our handleSubmit function (which is triggered when the form is submitted) prevents the default form submission behavior, and sends a POST request with the user-entered info to the server in JSON format.
Find elsewhere
🌐
Rip Tutorial
riptutorial.com › sending and receiving json data via post
JavaScript Tutorial => Sending and Receiving JSON Data via POST
Methods on the Response object such as .json() can be used to wait for the response body to load, then parse it. const requestData = { method : 'getUsers' }; const usersPromise = fetch('/api', { method : 'POST', body : JSON.stringify(requestData) }).then(response => { if (!response.ok) { throw new Error("Got non-2XX response from API server."); } return response.json(); }).then(responseData => { return responseData.users; }); usersPromise.then(users => { console.log("Known users: ", users); }, error => { console.error("Failed to fetch users due to error: ", error); });
Top answer
1 of 2
1

In your example, the webhook.site service you're attempting to connect to with your JavaScript isn't enabled (by default) with the proper CORS headers that modern browsers respect & enforce to improve user security. The developer console in your browser of choice should point this out to you; the error mine gave back was:

Access to XMLHttpRequest at 'https://webhook.site/5c7a5049-9c5e-4bf7-b1cf-0e05f6503bfa' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

As the error states, the requested resource doesn't respond with any valid Access-Control-Allow-Origin header, which will prevent the POST itself from being fully executed. In webhook.site, you can select the CORS Headers tickbox from the top of the user interface to enable the service to send the proper CORS headers to get this working.

Copylet xhr = new XMLHttpRequest();

xhr.open("POST","https://webhook.site/5c7a5049-9c5e-4bf7-b1cf-0e05f6503bfa",true); // configuration interface at https://webhook.site/#!/5c7a5049-9c5e-4bf7-b1cf-0e05f6503bfa/e14fc471-4bc4-410f-b16a-0755a231fb12/1

xhr.setRequestHeader("Content-Type", "application/json");

let data = JSON.stringify({'eventType' : 'test'});

xhr.send(data);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 2
-1

I suggest you to use axios, it gonna be something like this and you will get the response from your post request

Copyconst response = await axios.post('https://webhook.site/4530328b-fc68-404a-9427-3f2ccd853066/', {'eventType' : 'test'});
🌐
Attacomsian
attacomsian.com › blog › xhr-json-post-request
How to send JSON request using XMLHttpRequest (XHR)
October 12, 2022 - const xhr = new XMLHttpRequest() // listen for `load` event xhr.onload = () => { // print JSON response if (xhr.status >= 200 && xhr.status < 300) { // parse JSON const response = JSON.parse(xhr.responseText) console.log(response) } } // create a JSON object const json = { email: 'eve.holt@reqres.in', password: 'cityslicka' } // open request xhr.open('POST', 'https://reqres.in/api/login') // set `Content-Type` header xhr.setRequestHeader('Content-Type', 'application/json') // send rquest with JSON payload xhr.send(JSON.stringify(json))
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-post-json-data-to-server
How to Post JSON Data to Server ? - GeeksforGeeks
August 1, 2024 - The Frontend structure of our application is simple, with two inputs: one for name and one for email. A send button for sending the input data to the server. When the user hits the send button it makes a POST request with JSON data to the /data route on the server, and then the server logs the received data.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-send-a-json-object-to-a-server-using-javascript
How to send a JSON object to a server using Javascript? | GeeksforGeeks
January 17, 2022 - So we are using JSON.stringify() function to convert data to string and send it via XHR request to the server. Below is the sample code. ... function sendJSON(){ let result = document.querySelector('.result'); let name = document.querySelec...
🌐
ReqBin
reqbin.com › req › nodejs › 4rwevrqh › post-json-example
Node.js | How do I post JSON to the server?
To post JSON data to the server using Node.js, you need to provide the JSON data in the HTTP POST request body and pass the "Content-Type: application/json" request header. The Content-Type request header specifies the media type for the resource ...
🌐
Apidog
apidog.com › blog › jquery-post-json
How to Use jQuery to Post JSON Data?
February 9, 2026 - Learn how to use jQuery to post JSON data to an API with this comprehensive guide. Includes step-by-step instructions, best practices, and more.
🌐
Apidog
apidog.com › blog › fetch-post-json
How to Fetch POST JSON Data
February 1, 2026 - The Fetch API is used to make requests to servers and receive responses in a format such as JSON, XML, or HTML. Here is an example of how to use the Fetch API to POST JSON data:
🌐
freeCodeCamp
freecodecamp.org › news › javascript-post-request-how-to-send-an-http-post-request-in-js
JavaScript POST Request – How to Send an HTTP POST Request in JS
November 7, 2024 - At this point, you have learned how to use the two JavaScript inbuilt methods to send POST HTTP requests. Let’s now learn how to use Axios and jQuery. Axios is an HTTP client library. This library is based on promises that simplify sending asynchronous HTTP requests to REST endpoints. We will send a GET request to the JSONPlaceholder Posts API endpoint.
🌐
DEV Community
dev.to › ldakanno › making-a-post-request-using-json-server-h7c
Making a POST request using json-server - DEV Community
December 11, 2022 - Once your json-server is set up and has some data, you are going to create a basic POST request. There are a few requirements to make a post request. Alongside the URL you will be posting to, you need to also have a configuration object that will pretty much explain what the post request will be.
🌐
Codedamn
codedamn.com › news › javascript
How to Send a HTTP Post Request in JavaScript
June 3, 2023 - It's based on Promises, which makes it easy to use and provides several useful features over the native Fetch API, such as automatic JSON data transformation and request and response interception. To use Axios, you'll first need to install it via npm: ... const axios = require("axios"); // Define the data we want to send const data = { name: "Alice", age: 22 }; // Send the POST request using axios axios .post("https://api.example.com/data", data) .then((response) => console.log("Success:", response.data)) .catch((error) => console.error("Error:", error));
🌐
Ultimate Courses
ultimatecourses.com › blog › fetch-api-post-json
Using Fetch to Post JSON data - Ultimate Courses
May 20, 2020 - What’s different from a typical fetch call? You can see that we’ve had to specify a Content-Type header and set the value to application/json. Don’t forget the method: 'POST' or you won’t be posting anything.