Drumnbass Drumnbass - 5 months ago 11
Ajax Question

$http ajax AngularJS POST returns undefined index in PHP

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

Answer

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);
}
Comments