2

I am stuck a long time with trying to send a JSON from javascript to a PHP script : the sending is fine (I can see the JSON in fiddler) yet I receive nothing in the PHP script :

javascript:

var person = {
  name: 'yoel',
  age: 28
};
xmlhttp.open("POST","http://localhost:8888/statisticsdb.php",true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify(person));   

php :

echo 'trying to print ' . var_dump($_POST["name"]);

I would expect obviously to see SOMETHING but var_dump returns nothing. Help would be much appreciated!

1
  • 1
    you could use jQuery, it has a very simple $.post() method where you can simply pass the JSON Object as parameter: $.post('URL',person,success:function()) Commented Sep 3, 2012 at 14:03

3 Answers 3

6

try:

$data = json_decode(file_get_contents('php://input'));
var_dump($data->name);

the reason for this is, that the body of your POST-request is:

{"name":"yoel","age":28}

though, php expects something like (ref):

name=yoel&age=28

The json string can not be parsed properly, and thus $_POST will be empty.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick and helpful reply , much appreciated!
2

$_POST holds value decoded from request having Content-Type application/x-www-form-urlencoded, i.e. it parses:

param1=value1&param2=value2

into:

array( 'param1' => 'value1', 'param2' => 'value2')

If you send data in json format, you have to json_decode it from the raw php input:

$input = file_get_contents('php://input');
$jsonData = json_decode($input);

And you'll have a PHP object filled with your json stuff.

Comments

0

Add this:

xmlhttp.setRequestHeader("Content-length", JSON.stringify(person).length);

1 Comment

I don't think this solves the problem - there is already an accepted solution, also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.