Created
October 20, 2016 07:15
-
-
Save jens1101/4127c8f2c6200ba7b5dabf161a3df5a2 to your computer and use it in GitHub Desktop.
Posting data to Codeigniter via pure Angularjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class User | |
{ | |
public function save() | |
{ | |
$username = $this->input->post('name'); | |
$userData = json_decode($this->input->post('data')); | |
$doStuff($username, $userData); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
}); | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:'Content-Type': 'application/x-www-form-urlencoded'
will inform the receiving server that the posted data is form data$httpParamSerializer
serialises the data as form dataThose 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:
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()
.$_POST
with JSON data.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.