I have a simple xmlhttprequest with AJAX and want to rebuild this with PHP.
var data = {};
var payload = {
"flags" : true,
"codes" : true,
"units" : true
};
data.payload = JSON.stringify(payload);
$.ajax({
type : 'POST',
url : 'http://httpbin.org/post',
data : data,
success : function(response) {
var arr = JSON.stringify(response);
document.getElementById('placeholder').innerHTML = arr;
}
});
This works fine!
Now my Version with PHP:
$data = array(
'payload' => array(
'flags' => true,
'codes' => true,
'units' => true
)
);
$options = array(
"http" => array(
"method" => "POST",
"header" => "Content-Type: application/json\r\n",
"content" => json_encode($data)
)
);
$url = "http://httpbin.org/post";
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
var_dump($response);
When I compare the results there is a difference in the structure. Ajax looks like this:
{"form":{"payload":"{\"flags\":\"true\",
and PHP looks like this:
{"form": {},..."data": "{\"payload\":{\"flags\":\"true\",
Why is in PHP the "form" empty? I've tried it an extra Array "form", but when I look at the result there is a second "form" in the string.
JSON.stringifythe 'data'?$.ajaxaccept perfect an object directly.