gdfgdfg gdfgdfg - 4 months ago 39
AngularJS Question

Request and response with Angular $post and PHP Codeigniter

I have a problem when I am sending data to Codeigniter via Angular $post. I am using this JS code:

$scope.user.first_name = 'first name';
$scope.user.last_name = 'last name';

$http({
method: 'POST',
url: '/registration',
data: {user: $.param($scope.user)},
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
}).then(function successCallback(response) {
console.log(response)
}, function errorCallback(response) {
console.log(response);
});


My PHP is based from another answer from StackOverflow, but still doesn't work:

echo file_get_contents('php://input');
var_dump($this->input->post());


, but in this way I see response empty array, if I say:

var_dump($this->input->post('user'));


I see response NULL, Same is and with:

var_dump(json_encode($this->input->post()));


with or without key "user". Even if I use:

var_dump($_POST);


for the response I get empty array.

How to send and get data via $post Angular service with Codeigniter ?

Answer

If you want to send as form encoded data you need to serialize the whole data object with $.param()

Change:

 data: {user: $.param($scope.user)},

To

 data: $.param(angular.copy({user: $scope.user})),

Or use $httpParamSerializerJQLike

If you use defaults of $http would just be

 $http.post( '/registration',$scope.user).then(...

And in php

$data = json_decode(file_get_contents('php://input'));