Getting data from AngularJS to PHP

So .. this took more time then expected !

Of all the things I have to do, I never expected to spend so ‘much’ time on this one.

On the Angular side I post using this:

$scope.user = {email: 'john@doe.com', password: 'foobar'};

$scope.login = function () {
$http
.post('/api/auth.gettoken', $scope.user)
.success(function (data, status, headers, config) {
console.log(data);
if(data.ok === true) {
$window.sessionStorage.token = data.token;
$location.path('/user/home');
} else {
$scope.error = 'Error: Invalid user or password';
}
})

Now this led to to believe that this was now available using $_POST[‘email’] and $_POST[‘password’].

This was not the case, and has been subject of debate for some time it seems.

It’s sort of confusing because at first I didn’t get what was wrong since FireBug shows this just like any other POST:

What’s going on behind the scenes is that Angular posts this as application/json where jQuery uses the all so common application/x-www-form-urlencoded.

Most users solve this by modifying the behavior on the Angular side, but I went with their approach and changed the PHP side.

Normally the way to access POST or GET variables in Slim is to use

$app->request->params('paramName');

Since Angular sends the JSON in the body, I needed to get it from there.

I created this little helper function:

Class Helper {

/*
* Angular posts JSON in body, not in $_POST, use this to get
* the values and extract !
*/
public static function getJSONFromBody($app, $req_values = array()) {
$request = json_decode($app->request()->getBody(), true);
$res = array();

/* If no array is passed return associative array */
if(empty($req_values)) {
foreach ($request as $req => $value) {
$res[$req] = $value;
}
} else {
// We have an array, return in exact
// same order so we can list()
$i = 0;
foreach($req_values as $key) {
$res[$i] = (isset($request[$key]) ? $request[$key] : null);
$i++;
}
}
return $res;
}

}

This allows me to get the Angular variables from anywhere in my code:

list($email, $password) = Helper::getJSONFromBody($app,['email','password']);
echo 'Hello there ' . $email;

Thank you for reading. I hope you enjoyed my POST. (Get it?!)

Sam

A single golf clap? Or a long standing ovation?

By clapping more or less, you can signal to us which stories really stand out.