I\'ve read a few questions about the subject here on but couldn\'t find the answer I\'m looking for. I\'m doing some $.post with jQuery to a PHP5.6 server.
$
My mistake, the suggested worked, I got side tracked in the comments with JSON.stringify which caused the error. Bottom line: it works with either json_decode(json_encode($post)) or $post=(object)$post; The answer Michael gave is correct but side tracked me and I left the error in my code. JSON.stringify is only useful when posting the data from a form as I replied in the comment.
Receiving serialized/urlencoded POST data in the request's POST body as you are, you've correctly transformed it into an array with parse_str()
already.
However, the step of encoding then decoding JSON in order to transform that into the object (as opposed to array) you're looking for is unnecessary. Instead, PHP will happily cast an associative array into an object of class stdClass
:
parse_str(file_get_contents("php://input"), $data);
// Cast it to an object
$data = (object)$data;
var_dump($data);
A little more information is available in the PHP documentation on type casting.
In order to send raw json data, you have to stop jQuery from url-encoding it:
data = {"a":"test", "b":{"c":123}};
$.ajax({
type: 'POST',
url: '...',
data: JSON.stringify(data), // I encode it myself
processData: false // please, jQuery, don't bother
});
On the php side, just read php://input
and json_decode
it:
$req = file_get_contents("php://input");
$req = json_decode($req);