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.
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.
Share Improve this question edited Apr 27, 2016 at 9:25 Damjan Pavlica 33.9k10 gold badges75 silver badges78 bronze badges asked Jun 28, 2014 at 15:46 Jérôme VerstryngeJérôme Verstrynge 59.5k95 gold badges294 silver badges466 bronze badges 10 | Show 5 more comments2 Answers
Reset to default 290Sending 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.
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
XMLHttpRequest
. The name notwithstanding, you can use it for JSON data (and that is actually how jQuery does it in the background). – elixenide Commented Jun 28, 2014 at 15:48sending
an ajax request, which is a quite general thing. This one is asking forsending
but andreceiving JSON
in pure JavaScript. Furthermore, in order to send this JSON back, you have to know how to solve this part of the problem on theserver-side
which is another thing not mentioned on referenced question. – hex494D49 Commented Jul 1, 2014 at 12:32onreadystatechange
is what you use to emulateonload
, as shown by the accepted answer below. For parsing, you just useJSON.parse()
(again, as shown in the answer), but I was assuming that you already knew that since you mentioned stringifying in the question. I have tried to help you by pointing you to not 1 but 2 questions covering these points. There's obviously some difference -- rarely are 2 questions exactly identical -- but it's trivial if you already know how to stringify and parse JSON. That said, since you and @hex494D49 disagree, I am nominating this for reopening. – elixenide Commented Jul 1, 2014 at 15:00