1

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);        
  }
5
  • 1
    application/x-www-form-urlencoded is not capable of any complex structures, only key-value string pairs. Consider using application/json instead. Either way, you need to json_decode() the result of file_get_contents() in your PHP code. Commented Aug 11, 2017 at 19:36
  • but it shows the following error "XMLHttpRequest cannot load localhost/learn_php/api/api_set_data. Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response." Commented Aug 11, 2017 at 19:38
  • So configure your "Access-Control-Allow-Headers" in server side Commented Aug 11, 2017 at 19:39
  • @UsamaIshaque You should get that error either way. That indicates that the form is being served from something other than localhost. Commented Aug 11, 2017 at 19:40
  • solved header issue as well as used json_decode instead of json_encode but still getting the same output like this { user_id: false, data: "[73,66,75,70,94,100,60,89,69,79]" } Commented Aug 11, 2017 at 19:45

1 Answer 1

2

Use JSON.stringify and json_decode respectively

Javascript

data: JSON.stringify($scope.data)

PHP

$array['data'] =  json_decode(file_get_contents("php://input"), true);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.