NHTorres
NHTorres

Reputation: 1538

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

Upvotes: 2

Views: 5319

Answers (1)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76433

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

Upvotes: 10

Related Questions