What is the correct way to send JSON string between javascript and PHP?

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 the response again as a Json string, but I am running into tons of problems and different methods that just won't work together, that's what worked still:

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 couldn't be easier, but I am getting this warning:

[09-Jan-2015 15:50:03 America / Mexico_City] PHP Deprecated: Auto-complete $ 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 php: // input stream instead. in Unknown on line 0

[09-Jan-2015 15:50:03 America / Mexico_City] PHP Warning: Unable to change header information - headers have already been sent Unknown on line 0

And of course the response text looks like this:

Deprecated : $ HTTP_RAW_POST_DATA autocomplete 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 php: // input stream instead. c Unknown on line 0


Warning : Unable to change header information - headers already sent to unknown on line 0
{"Foo": "1", "bar": "2"} "

What am I doing wrong? Why is PHP complaining about headers already sent?

I am using PHP 5.6.

+3


source to share


2 answers


You need to edit your php.ini file and install always_populate_raw_post_data = -1

.

Your code is working fine. $json = file_get_contents('php://input');

is correct.



You only get a warning because your PHP has been updated and you need to update your php.ini file for this new version.

More info here: https://www.bram.us/2014/10/26/php-5-6-automatically-populating-http_raw_post_data-is-deprecated-and-will-be-removed-in-a-future- version /

+5


source


I looked at my old code that does Ajax without JQuery. To send Json in the POST parameter is no different than what you are already doing.

You really only need to change the header settings and give them a parameter name:

json_string = '{"foo":"1","bar":"2"}';

var r = new XMLHttpRequest();
r.open('post', 'script.php', true);
r.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
r.onload = function () {
    console.log(this.responseText);
};
r.send('json='+encodeURIComponent(json_string));

      



And then, of course, in PHP:

$_POST['json']

      

Edit: Added encodeURIComponent()

.

+1


source







All Articles