2

I'm sending data to an API REST service via the ajax $http service of AngularJS but php always says that the index is undefined. I've checked a lot of posts on SO that ask for the same error and I tried everything that they say but I still get the same error.

How I'm using the $http service:

$http({
    method: 'POST',
    url: window.location.pathname+'/../../api/tasks/'+$id,
    data: {
        'title': $scope.allData.taskData[0].title,
        'content': $scope.allData.taskData[0].content,
        'usersInTask': $scope.allData.taskUsers
    },
    contentType: 'application/json',
    dataType: 'json',
    headers: {'Content-Type': 'application/json'}
})
.then(function success(response){

    $scope.closeDialog();
}, function error(response){
    console.log("Error:" +response.statusText);
});

How I try to get values in PHP:

$title = $_POST['title'];
$content = $_POST['content'];
$users = $_POST['users'];

In this case, for example, it always says that title is an undefined index of $_POST

2 Answers 2

2

To read data first you need to decode it in POST format.

$json_input = file_get_contents('php://input');

if ($json_input) {
    $_REQUEST = json_decode($json_input, true);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Since you are posing data it application/json format you need to read it from raw POST data. Try this:

$postData = json_decode(file_get_contents("php://input"));
$title = $postData->title;
$content = $postData->content;

1 Comment

I was able to get the data like that, but trying to access to its elements it just said "Notice: Trying to get property of non-object"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.