Usama Ishaque
Usama Ishaque

Reputation: 131

POST array from angular to php

I am posting an array from angular to PHP. The array i sent is like that [92,70,86,62,75,84,95] but in php it's turned into like this - "[92,70,86,62,75,84,95]".

My expected output from php is

{ user_id: false, data: [92,70,86,62,75,84,95] } The output i am getting is { user_id: false, data: "[92,70,86,62,75,84,95]" }

The code for posting data from angular is

$scope.data = [92,70,86,62,75,84,95];
 $http({
         method: 'POST',
         url: 'http://localhost/learn_php/api/api_set_data/',
         data: $scope.data,
         headers: {
             'Content-Type': 'application/x-www-form-urlencoded'
           }
        })
        .success(function(data) {
           console.log(data);
        });

The code in php is

public function api_set_data(){

    $array['user_id']  = $this->session->userdata('user_id');
    $array['data'] =  file_get_contents("php://input");

    $serializedData = serialize($array);
    file_put_contents(APPPATH."assets/get_values.txt", $serializedData);

    echo json_encode($array);        
  }

Upvotes: 1

Views: 1407

Answers (1)

BeetleJuice
BeetleJuice

Reputation: 40886

Use JSON.stringify and json_decode respectively

Javascript

data: JSON.stringify($scope.data)

PHP

$array['data'] =  json_decode(file_get_contents("php://input"), true);

Upvotes: 2

Related Questions