Receiving JSON with PHP via $http.post()

Asked

Viewed 2,343 times

1

I want read a JSON in PHP received from a function $http.post() from Angularjs, I’ve tried using json_decode() and set up the header (both in PHP and Angular) but it didn’t work. PHP accuses it to be an undefined index, I tried to use var_dump and it returns NULL.

Angular

$http.post(path, $scope.meuJson, {
            headers: {
                'Content-Type': 'application/json'
            }
        }).success(function(response) {
            ... 
        })

PHP

header('Content-type: application/json');
$json = json_decode($_POST['meuJson']);

var_dump($_POST)

array(0) {
}


OBS: I can see the data being sent as payload of my request by Network

  • of a var_dump($_POST) and add the result to your question

  • This return is not a json

  • 1

    I don’t know anything about angular, but if you pass the value of $scope.meuJson, how would the framework know with which key this would be posted? As @Erloncharles suggested, edit the question with the output of var_dump($_POST) to clarify this.

  • Post the format of mdados you want to send, do not need to be exactly the data

1 answer

3


You cannot get the angular data via $_POST, because they are not serialized as parameters in the request body.

To get the body of the request, read the data this way:

$meuPost = file_get_contents("php://input");

$json = json_decode( $meuPost );

The php://input is an entry for the body of the raw request sent by the browser, before parse by PHP. Roughly, it would be comparable to reading the stdin in a local application (not the same thing, but to illustrate what happens).

  • 1

    Could explain the "php://input" function does?

  • @Yurijeanfabris gave a brief explanation, then I make an elaborate one, as soon as I have some free time.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.