0

I'm having trouble retrieving or sending data with POST using PHP and angular. I reduced my problem to the easiest case but still the response is an empty array.

Here is my Angular code:

this.search = function() {
    console.log("searching");
    $http({
        method: 'POST',
        url: 'search/',
        data: {search:1, direct: true}
    }).then(function successCallback(response) {
        console.log(response.data);
    }, function errorCallback(response) {
        console.log("Error retrieving data.");
        console.log(response);
    });
}

and my PHP code:

<?php

header('Content-type: application/json');

echo json_encode($_POST) ;

?>

The funny thing is that using GET in both places, it works :/

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vandervals
  • 5,774
  • 6
  • 48
  • 94
  • Most likely related to http://stackoverflow.com/questions/19254029/angularjs-http-post-does-not-send-data – JCOC611 Oct 05 '15 at 14:44

1 Answers1

3

Angular serializes js objects into JSON to POST, php does not populate the $_POST data structure from a JSON post body, to ge the json data in the post body you'll have to read from php://input

<?php

header('Content-type: application/json');

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

?>
Musa
  • 96,336
  • 17
  • 118
  • 137
  • Why does angular send your js object as json? maybe because json is sexier than urlencoded form data(just a guess). Unless you send the data as `application/x-www-form-urlencoded` or `multipart/form-data` you can't use $_POST, (except if you do `$_POST = json_decode(file_get_contents('php://input'),true);`). I'm no angular expert but there are ways to get the data to send as form data and use $_POST, I do however think that any performance gain or loss will be negligible. – Musa Oct 05 '15 at 15:22
  • and how do you convert that to an array? I've tryed with `json_decode`, but something weird happens... – Vandervals Oct 05 '15 at 15:25
  • 1
    Did you set the second parameter of json_decode to true – Musa Oct 05 '15 at 15:29