Skip to content

Instantly share code, notes, and snippets.

@jens1101
Created October 20, 2016 07:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jens1101/4127c8f2c6200ba7b5dabf161a3df5a2 to your computer and use it in GitHub Desktop.
Save jens1101/4127c8f2c6200ba7b5dabf161a3df5a2 to your computer and use it in GitHub Desktop.
Posting data to Codeigniter via pure Angularjs
<?php
class User
{
public function save()
{
$username = $this->input->post('name');
$userData = json_decode($this->input->post('data'));
$doStuff($username, $userData);
}
}
angular.module('app').service('User', fuonction($http, $httpParamSerializer) {
this.saveUser = function(username, complexObjectData) {
return $http({
url: 'https://example.com/user/save',
method: 'POST',
data: $httpParamSerializer({
name: username,
data: complexObjectData //This will automatically be serialized as JSON
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded' //This is necessary so that $_POST will be populated
}
});
};
});
@jens1101
Copy link
Author

More Info About the Implementation

Angular (by default) posts data as JSON. This is great... except for PHP. PHP's $_POST only gets populated (by default) via form data. So if you post JSON data then it won't know what to do with it. The above code, basically, submits your data as form data. There are two key features that you should note:

  • The 'Content-Type': 'application/x-www-form-urlencoded' will inform the receiving server that the posted data is form data
  • The $httpParamSerializer serialises the data as form data

Those two combined emulate a form post and therefore $_POST will get populated (and by extension Codeigniter's $this->input->post()).

Alternatives

The above is quite verbose, especially if you want to use this everywhere. There are a few alternative approaches that I can think of:

  • Set the default Content-Type in the Angular config and auto-wrap all posted data with $httpParamSerializer. Then you don't need to bother with writing it out each time and you could use the shorthand $http.post().
  • Configure PHP to populate $_POST with JSON data.
  • In PHP You can use file_get_contents("php://input"); to work with the raw posted data, but this prevents you from using Codeigniter's convenience functions, and may even be a security risk.

I personally haven't tried any of the above alternatives, but those are just different approaches that I saw while searching for a solution to this problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment