0

I am really new to Angular. I am trying to pass a variable to php but the response is " Notice: Trying to get property of non-object" and null for the array.

js file:

var myData = {
            fruit1: 'apple',
            fruit2: 'banana'
        };


$http({
    url: "test.php",
        method: "POST",
        headers : { 'Content-Type': 'application/json' },
        data: myData
    }).success(function(data, status, headers, config) {
        $scope.data = data;
    }).error(function(data, status, headers, config) {
        $scope.status = status;
});

php file:

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$data = $request->myData;

var_dump($data);
halfer
  • 19,824
  • 17
  • 99
  • 186
goyangi96
  • 11
  • 2
  • Check the network tab in the Developer Console to see if the request sent is actually a POST request and not an OPTIONS request. – georgeawg May 18 '19 at 14:19
  • Possible duplicate of [Angular HTTP post to PHP and undefined](https://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined) – random_user_name May 18 '19 at 17:10

1 Answers1

0

The .success and .error methods have been removed from the AngularJS framework. Instead, use the .then and .catch methods:

var myData = {
    fruit1: 'apple',
    fruit2: 'banana'
};

$http({
    url: "test.php",
    method: "POST",
    ̶h̶e̶a̶d̶e̶r̶s̶ ̶:̶ ̶{̶ ̶'̶C̶o̶n̶t̶e̶n̶t̶-̶T̶y̶p̶e̶'̶:̶ ̶'̶a̶p̶p̶l̶i̶c̶a̶t̶i̶o̶n̶/̶j̶s̶o̶n̶'̶ ̶}̶,̶
    data: myData
}).then(function(response) {
    $scope.data = response.data;
    return response.data;
}).catch(function(err) {
    $scope.status = err.status;
    throw err;
});

The $http service automatically JSON encodes data and automatically sets the content type to application/json.

In this case, the code does not use the promise returned by the .then and .catch methods. If the promise is used, it is important to have return and throw statements in the success and rejection handlers.

php file:

$postJSON = file_get_contents("php://input");
$dataArr = json_decode($postJSON, TRUE);

var_dump($dataArr);

The JSON encoded data is found in the body of the POST request. The name of the variable is not sent, only the contents.

The second argument of the json_decode function, specifies that objects be converted to associative arrays.

Keep in mind that these POST requests are subject to same-origin policy. The XHR request must be made from a website page that has the same origin as the page receiving the POST request.

Community
  • 1
  • 1
georgeawg
  • 48,608
  • 13
  • 72
  • 95