I have been directed to use the method php://input
instead of $_POST
when interacting with Ajax requests from JQuery. What I do not understand is t
php://input
can give you the raw bytes of the data. This is useful if the POSTed data is a JSON encoded structure, which is often the case for an AJAX POST request.
Here's a function to do just that:
/**
* Returns the JSON encoded POST data, if any, as an object.
*
* @return Object|null
*/
private function retrieveJsonPostData()
{
// get the raw POST data
$rawData = file_get_contents("php://input");
// this returns null if not valid json
return json_decode($rawData);
}
The $_POST
array is more useful when you're handling key-value data from a form, submitted by a traditional POST. This only works if the POSTed data is in a recognised format, usually application/x-www-form-urlencoded
(see http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4 for details).