Request and response using Angular $ post and PHP Codeigniter

I am having a problem when I send 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 on another answer from StackOverflow, but still not working:

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

but this way I see the answer is an empty array if I say:

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

I see a NULL answer, Same thing with:

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

with or without a key. Even if I use:

var_dump($_POST);

for the answer, I get an empty array.

How to send and receive data through the $ post Angular service using Codeigniter?

+4
source share
1 answer

If you want to send data in the form of a form, you need to serialize the entire data object using $.param()

Edit:

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

For

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

Or use $httpParamSerializerJQLike

$http,

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

php

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

Source: https://habr.com/ru/post/1649100/


All Articles