2

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

NHTorres
  • 1,528
  • 2
  • 21
  • 39
  • look at this one http://stackoverflow.com/questions/8207488/get-all-variables-sent-with-post – nahab Nov 27 '15 at 16:01
  • 1
    JSON data doesn't map to `$_POST` automatically, for that you need to send the data as `application/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 Nov 27 '15 at 16:08

1 Answers1

9

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
n3hl
  • 87
  • 1
  • 12
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • Apply what you mentioned and it works, but reach values is as follows, edit my post – NHTorres Nov 27 '15 at 16:21
  • @sioesi: Get the actual array using `$postData['post']`, that's what the JSON you posted looks like: `$postData['post']['hash']` will give you the hash. – Elias Van Ootegem Nov 27 '15 at 16:26
  • 1
    @Yes! Thank you very much !, This worked very well for me. Now just as certainly as if he sent the parameters in json format could not read them as such in PHP? that came as null? – NHTorres Nov 27 '15 at 16:27
  • 1
    @sioesi: I don't understand your comment... at all. Who is _"he"_ in your comment? do you want to know how you know what would happen in if the JSON you're decoding is invalid? in that case check if `json_last_error() !== JSON_ERROR_NONE`. If that is true, `json_last_error_msg` will give you an error string. Also check `$_SERVER["CONTENT_TYPE"]`, if it isn't set to `application/json`, the post body might not contain valid json – Elias Van Ootegem Nov 27 '15 at 16:31