Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs - POST an array of objects(JSON data) to a PHP page

An example of how my JSON data is like:

$scope.a = [{
            "email": "keval@gmail",
            "permissions": {
                "upload": "1",
                "edit": "1"
            }
        }, {
            "email": "new@aa",
            "permissions": {
                "upload": "1",
                "edit": "1"
            }
        }];

I want to post the same, and here's my approach:

$http({
    method: 'POST',
    url: 'backend/savePermissions.php',
    data: {
        mydata: $scope.a
    },
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
})
.success(function(data) {
    console.log(data);
});

And the PHP is to take the request and respond:

echo $_POST['mydata'];

I tried JSON.stringify before the call and json_decode while echoing it back; still didn't work. Been trying all the possibilities I can think of, and what I find on the web/other questions, but still not working.

like image 581
Keval Avatar asked Mar 04 '15 09:03

Keval


3 Answers

I've made plnkr for you http://plnkr.co/edit/K8SFzQKfWLffa6Z4lseE?p=preview

$scope.postData = function () {
    $http.post('http://edeen.pl/stdin.php', {user:$scope.formData}).success(
      function(data){
        $scope.response = data
      })
  }

as you can see I'm sending a raw JSON without formating it, then in php

<?php
  echo file_get_contents('php://input');

I read the JSON directly and echo it but you can do whatever you want

read more about php://input here http://php.net/manual/en/wrappers.php.php

I was using it for a long time for REST services to avoid transforming JSON to string to many times

like image 99
maurycy Avatar answered Oct 20 '22 11:10

maurycy


I use this, with which I can send Array JSON:

var array = {}
array['key1'] = value1;
array['key2'] = value2;

$http.post(URL, array)
  .success(function(data){
  })
  .error(function(){

});
like image 26
Antonio Reyes Montufar Avatar answered Oct 20 '22 13:10

Antonio Reyes Montufar


try using $httpParamSerializer or $httpParamSerializerJQLike

$http({
    method: 'POST',
    url: 'backend/savePermissions.php',
    data: $httpParamSerializer($scope.a),
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
})
.success(function(data) {
    console.log(data);
});
like image 34
Ben Hsieh Avatar answered Oct 20 '22 11:10

Ben Hsieh