First method
To send data from JavaScript to PHP (or any other script) should be just as you found out:
xhttp.setRequestHeader('Content-type', 'application/json');
xhttp.send(JSON.stringify(params));
where params
is some JavaScript variable. application/json
is the datatype for JSON data.
On the PHP side, you were also correct: use JSON_decode()
to get a PHP-equivalent to the JavaScript data you sent.
Second method (only for GET requests)
GET data is encoded in the URL, so an alternative way is to encode the data directly into the URL of the PHP script. (Don't do this for sensitive data.)
Javascript:
xhttp.open("GET", "phpfile.php?x=2&y=3&z=4");
PHP:
$x = $_GET["x"];
$y = $_GET["y"];
$z = $_GET["z"];
Because you seemed unclear on how to send multiple variables using the first method:
If you want to send multiple variables, put it into an object or array (because JSON.stringify()
only takes one (data) argument, not a comma-separated list of arguments).
// for example, to send the variables x, y, z
var xValue = 2;
var yValue = 3;
var zValue = 4;
xhttp.setRequestHeader('Content-type', 'application/json');
xhttp.send(JSON.stringify({ x: xValue, y: yValue, z: zValue }));
PHP:
$data = json_decode($_GET);
echo $data->x; // 2
echo $data->y; // 3
echo $data->z; // 4;
(disclaimer: code is untested; I'm not sure if data is received into the $_GET
variable. Use json_decode()
on the variable that PHP receives JSON data from.)