I am sending parameters using this method to my server php but I get the values that you post shipping:
function post(path, parameters) {
var http = new XMLHttpRequest();
console.log(parameters);
http.open("POST", path, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(parameters);
}
php :
public function tracking_referidos(){
$this->autoRender = false;
$result = array();
$result['post'] = $_POST;
echo json_encode($result);
exit;
}
result : {"post":{"referrer":"","event":"eventrid","hash":"45hfkabdus"}}
I am sending parameters using this method to my server php but I get the values that you post shipping:
function post(path, parameters) {
var http = new XMLHttpRequest();
console.log(parameters);
http.open("POST", path, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(parameters);
}
php :
public function tracking_referidos(){
$this->autoRender = false;
$result = array();
$result['post'] = $_POST;
echo json_encode($result);
exit;
}
result : {"post":{"referrer":"","event":"eventrid","hash":"45hfkabdus"}}
- look at this one stackoverflow./questions/8207488/… – nahab Commented Nov 27, 2015 at 16:01
-
1
JSON data doesn't map to
$_POST
automatically, for that you need to send the data asapplication/x-www-form-urlencoded
(key=value&key2=value2
and so on). Alternatively, you can get the raw POST data, which is a JSON string like so:file_get_contents('php://input');
– Elias Van Ootegem Commented Nov 27, 2015 at 16:08
1 Answer
Reset to default 10You're sending a JSON string. PHP doesn't decode that data and map it to the $_POST
super global automatically. If you want PHP to do that, you need to send the data as application/x-www-form-urlencoded
(ie similar to the URI of a get request: key=value&key2=value2
).
You can send data using the application/json
content type, but to get at the request data, you need to read the raw post body. You can find that in the php://input
stream. Just use file_get_contents
to read it:
$rawPostBody = file_get_contents('php://input');
$postData = json_decode($rawPostBody, true);//$postData is now an array