Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$_POST array empty in PHP after an a request with post data

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"}}

like image 556
NHTorres Avatar asked Sep 15 '26 13:09

NHTorres


1 Answers

You'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
like image 192
Elias Van Ootegem Avatar answered Sep 18 '26 03:09

Elias Van Ootegem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!