0

How can I send a POST request along with a JSON array to main.php to return the value of key_1? My current method below doesn't work and I can't figure out how to fix this.

script.js:

var array = {};
array["key_1"] = "obj_1";
array["key_2"] = "obj_2";
array["key_3"] = "obj_3";

var http = new XMLHttpRequest();
http.open("POST", "main.php");
http.onload = function () {
    document.querySelector("p").innerHTML = this.responseText;
}
http.send(array);

main.php:

<?php
    $params = json_decode(file_get_contents("php://input"));
    echo ($params["key_1"]);
?>

index.html:

<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <p></p>
</body>
</html>
aman
  • 307
  • 21
  • 48

2 Answers2

5

file_get_contents() does not parse the content. You need to pass the value through json_decode().

<?php
    $params = json_decode(file_get_contents("php://input"), true);
    echo ($params["key_1"]);
?>
emarref
  • 1,286
  • 9
  • 18
2

In main.php, use this code:

<?php
    $params = json_decode(file_get_contents("php://input"));
    echo $params->key_1;
?>

When you decode a JSON string, you convert it to an object of stdClass.

If you want to decode JSON and convert it to an array, use code below:

<?php
    $params = json_decode(file_get_contents("php://input"), true);
    echo $params['key_1'];
?>
Silvio Delgado
  • 6,798
  • 3
  • 18
  • 22