0

I created a ajax request in Javascript using json, but the $_POST variable is empty.

var userid = "james";
var score = 200; 
var jsondata = {
userid: userid,
score: score
};
data = JSON.stringify(jsondata);
req = new XMLHttpRequest();   
req.setRequestHeader("Content-Type", "application/json");
req.open("POST", 'functions.php', true);
req.send(data); 

My functions.php file looks like this:

print "CONTENT_TYPE: " . $_SERVER['CONTENT_TYPE'] . "<BR />";
$data = file_get_contents('php://input');
print "DATA: <pre>";
var_dump($data);
var_dump($_POST);
var_dump($_GET);

However all of this gives me an empty array. Any help, please?

Android Ninja
  • 811
  • 1
  • 6
  • 9

3 Answers3

0

I think you are sending data incorrectly,

Use,

req.send("name=James"); 
vaibhavmande
  • 1,115
  • 9
  • 17
0

$_POST only gets populated for form encoded and multipart encoded data. Your data is encoded as JSON and should be accessed through php://input (as per this question).

$data should contain the JSON. If it doesn't, then it is probably due to you failing to set the Content-Type header of the request.

req.setRequestHeader("Content-Type", "application/json");
Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thank you for your help. I added req.setRequestHeader("Content-Type", "application/json"). I also tried req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); but php://input still shows an empty array. – Android Ninja Apr 06 '15 at 23:51
0

Except that the line req.setRequestHeader("Content-Type", "application/json"); should be under req.open("POST", 'functions.php', true);because the state of the XHR object must be open to set a header, your code is perfectly operational.

Your problem is somewhere else.

  • How do you check what is your php displaying ?
  • Is your ini conf. appropriate ? Try to do ini_set("allow_url_fopen", true); before file_get_contents('php://input');
  • Check the paramter post_max_size in your php.ini. it should be 8M or 10M (no MB but M and only M, or php will interpete it as 0)

The best way to check the interpreted parameters of php.ini is to do an empty .php file with <?php phpinfo(); ?> and launch it; Then check the section "Core".

mathieu
  • 477
  • 3
  • 9