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 :/

1

1 Answer 1

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') ;

?>
Sign up to request clarification or add additional context in comments.

3 Comments

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.
and how do you convert that to an array? I've tryed with json_decode, but something weird happens...
Did you set the second parameter of json_decode to true

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.