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?
I think you are sending data incorrectly,
Use,
req.send("name=James");
$_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");
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.
ini_set("allow_url_fopen", true);
before file_get_contents('php://input');
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".