I am trying to send a tiny bit of data from javascript using XMLHttpRequest and a Json string to a PHP script to process it and return some response in the form of a Json string again, but I've ran into tons of issues and different methods that just won't work together properly, here's what has worked so far:
Client
json_string = '{"foo":"1","bar":"2"}';
var r = new XMLHttpRequest();
r.open('post', 'script.php', true);
r.setRequestHeader('Content-type','application/json; charset=utf-8');
r.setRequestHeader('Content-length', json_string.length);
r.setRequestHeader('Connection', 'close');
r.onload = function () {
console.log(this.responseText);
};
r.send(json_string);
Server
$json = file_get_contents('php://input');
echo $json;
It can't get simpler than this, however I'm getting this warning:
[09-Jan-2015 15:50:03 America/Mexico_City] PHP Deprecated: Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead. in Unknown on line 0
[09-Jan-2015 15:50:03 America/Mexico_City] PHP Warning: Cannot modify header information - headers already sent in Unknown on line 0
And of course the response text looks like this:
Deprecated: Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead. in Unknown on line 0
Warning: Cannot modify header information - headers already sent in Unknown on line 0
{"foo":"1","bar":"2"}"
What am I doing wrong? Why does PHP complain about already sent headers?
I'm using PHP 5.6.
$json = file_get_contents('php://input');You can't usephp://inputanymore. You have to put your json in a request parameter and read that parameter with$_POST.You can't use php://input anymore- explain what that means. I used it today.\php://inputis the correct method to use.