Angular and Drupal/PHP: Get $_POST data working (hint: It’s JSON!)

Published: 19.3.2014
Categories: Technology
Reading time: 1 min
We love Drupal T-shirt

Ok, the title says it all, but for all those blog prose aficionados amongst you, here’s the long version.

These days chances are you implement your frontend functionality in JavaScript as an AngularJSappOpens in a new tab (check it out!). In that case, you’ll probably want to connect your Angular app to fetch data from your backend (Drupal or PHP in general assumed). You’ll also probably supply some app parameters such as user input via data, for example in an HTTP post request with Angular’s default $http serviceOpens in a new tab, like that:

var request_data = {
 firstname: 'Quentin',
 lastname: 'Hapsburg'
};
$http.post(request_url, request_data)
 .success(request_success_callback)
 .error(request_error_callback);
// ...

Now on Drupal/PHP, you’re eventually going to try access that post data with good ‘ole $_POST superglobal (since we’re not dealing with Drupal’s form submission handling here):

$firstname = $_POST['firstname'];

BUT: This will simply result in an “index not defined” PHP notice because $_POST is an empty array – you simply can’t access your precious HTTP post data with your traditional means.

And that’s going to make you tear your hairs out – why in the world is $_POST data is plain empty, even in a simple non-Drupal PHP script?!?!

The explanation and solution are dead simples:

Angular’s $http.post is by default assuming and encoding your post data to be JSON, instead of ye ole querystring-formatted post data you and your PHP would expect as with a submit.

To access your Angular app’s post data in PHP (and Drupal) you have to read in the raw request payload and decode it from JSON into your beloved PHP array form (which you’d have your traditional $_POST data in):

$data = file_get_contents("php://input");
$data = json_decode($data, TRUE);

Hope this saved you some minutes or hours. Happy coding!

Related content

Loading...