1

I want to POST 3 parameters to my PHP web service. One of which is an array, so I used JSON.stringify() first and then added it as the parameter. The problem is, PHP isn't receiving the stringify'ed parameter.

My array is created by fetching IDs of each element in an object.

Converting it into a string:

var cid = JSON.stringify(cids);

Output as in the console for cid:

["1","2","3"]

And my $http.post call:

var dataObj = {
    wid: wid,
    type: type,
    cid: cid
};

$http.post("my.php", dataObj);

From what I understand, the array gets converted into a string, which must get POSTed alike other strings, but when I echo back $_POST['cid'], it turns out to be blank; while the wid & type are proper.

Keval
  • 3,389
  • 2
  • 24
  • 41

1 Answers1

2

From my understanding all post data is converted to JSON anyway. Manually changing your array to JSON and including is just the same as:

$http.post("my.php", {
        wid: wid,
        type: type,
        cid: [1, 2, 3]
    }

At the other side of the connection the JSON is converted back to objects(arrays) if possible. PHP doesn't print anything because arrays aren't converted to strings that well. Although you should expect the string 'array'. Try echo'ing $_POST['cid'][0]

EDIT:
As stated in the comments and this post the following code is required to get PHP and AngularJS to play together:

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
Community
  • 1
  • 1
Maarten Bicknese
  • 1,498
  • 1
  • 14
  • 27
  • Sorry. I tried to echo `$_POST['cid'][0]` and it still is blank. – Keval May 08 '15 at 08:38
  • @Keval Since you're using angular did you have a look at: http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined? – Maarten Bicknese May 08 '15 at 08:59
  • I did look at it, but I never gave it an attempt because rest of my fields were getting POST'ed except for the array I stringify'ed. I just tried and it worked. I don't get what was the issue. Although, I used `transformRequest` and got my code working. I can use $_POST and perform my functions. – Keval May 08 '15 at 09:12
  • Please edit your answer and add the PHP code in the post you linked me to. Thanks. – Keval May 08 '15 at 10:47