2

I was working on my first API/backoffice (so I'm really new with MAMP and PHP) and this is my problem : I used $http with post method on my script (I'm using AngularJS) and I send an object as data. My PHP was supposed to return what I've sent BUT I get this thing :

Array([{"id":1}] => )

And I've tried a lot of things so I don't know what to do. Here's my code

JS:

    $http({
    method:"POST",
    url:"api/getInfos.php",
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data:{id:1}
})
.then(function successCallback(response) {
    console.log(response.data);
    if(response.data!="null")
        $scope.presentation=response.data;
    else{
        $scope.presentation={title:"Error",content:"No content"};
    }
}, function errorCallback(response) {
    console.log("errorCallback");
});

PHP:

header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
header('Access-Control-Allow-Methods: GET, POST, PUT');
require "openConnection.php";

print_r($_POST);

Thanks !

EDIT : I solved my problem by using $post=json_decode(file_get_contents('php://input'),true). But, if you can find a solution and explain it to me you're welcome.

lvk
  • 131
  • 6
Romain Bouvet
  • 87
  • 1
  • 10
  • From what I can tell, you sent your data as JSON string `{"id":1}`. This was interpreted by PHP as the key of the first POST variable (PHP sees `$_POST` as an associative array) that had no value, resulting in an array with one key that had no value. When you use file_get_contents('php://input'), you will be given the raw post data instead of the interpreted result. This is the JSON string that you sent over which can then be decoded and used in your script. – Cas May 10 '16 at 10:47
  • Thanks man ! This is what I thought. – Romain Bouvet May 10 '16 at 13:19

0 Answers0