Sending a JSON to server and retrieving a JSON in return, without JQuery

JavascriptJsonPostGetXmlhttprequest

Javascript Problem Overview


I need to send a JSON (which I can stringify) to the server and to retrieve the resulting JSON on the user side, without using JQuery.

If I should use a GET, how do I pass the JSON as a parameter? Is there a risk it would be too long?

If I should use a POST, how do I set the equivalent of an onload function in GET?

Or should I use a different method?

REMARK

This question is not about sending a simple AJAX. It should not be closed as duplicate.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJ&#233;r&#244;me VerstryngeView Question on Stackoverflow
Solution 1 - Javascripthex494D49View Answer on Stackoverflow
Solution 2 - JavascriptJohn Balvin AriasView Answer on Stackoverflow