1

When Im sending post request to php - it return string to me and I can't do anything with it.

That's my request from JS:

axios.post("ajax.php", JSON.stringify(myObj))

That's how I get data (from JS) in PHP:

$data = $_POST;

And that's response of $data var_dump

array(1) {
  ["{"username":"rew","info":"rew"}"]=>
  string(0) ""
}

I need 2 variables. First username and second info. How can I do it? Is it possible to split this line? Or I sending in wrong format?

My full PHP code

$data = array(
  "userName" => $_POST['userName'],
  "pass" => $_POST['pass']
);
$opts = array(
  'http'=>array(
    'method'  => 'POST',
    'content' => json_encode($data),
    'header'  => "Content-Type: application/json\r\n" .
                 "Accept: application/json\r\n" .
                 "Authorization: Basic " . base64_encode("$username:$password"),
  )
);
$context = stream_context_create($opts);
$file = file_get_contents($remote_url, false, $context);
echo $file;

And var myObj

let myObj = {
    "username": "rew",
    "info": "rew"
};
  • use json_decode function. More info is here https://www.php.net/manual/en/function.json-decode.php – Nawin Oct 03 '19 at 16:16
  • Possible duplicate of [How to convert JSON string to array](https://stackoverflow.com/questions/7511821/how-to-convert-json-string-to-array) – Nawin Oct 03 '19 at 16:17

1 Answers1

-1

It seems you don't need to stringify the object. The default content-type with axios is going to be application/json, so this should work:

axios.post("ajax.php", myObj);

As to $_POST will only come content type application/x-www-form-urlencoded and multipart/form-data, you need to change your code to decode raw input:

json_decode(file_get_contents('php://input'), true);
freeek
  • 985
  • 7
  • 22