-3

I am using $http through AngularJS to send data to a PHP document which is intended to save the data in a MySQL database. However, the data is being decoded blank or undefined. The JSON makes it to the PHP file, as I can see the request headers, but the response is blank.

I have tried testing different variations of the code to make sure that the JSON-encoded data makes it to the PHP document, and it does, but when attempting to json_decode() it does not pull anything from the JSON.

PHP File

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$user = $request->Username;
echo $user;

AngularJS

$scope.submit = function() {
        $http({
            url: "http://www.walkermediadesign.com/planner3/src/ceremony.php",
            method: "POST",
            data: this.ceremony
        }).then(function successCallback(response) {
            console.log(response.data);
        }, function errorCallback(response) {
            $scope.error = response.statusText;
    })};

This is the post data:

$postdata = 
(2) [{…}, {…}]
0: {Username: "redphyre@gmail.com"}
1: {opening: "Friends and Family of BRIDE and GROOM, welcome and…d 
falling in love with each other all over again."}
length: 2
__proto__: Array(0)

There are no error messages or 500 errors, just blank data being returned.

Matthew Walker
  • 193
  • 1
  • 15
  • missed a `;` so I fixed that, but that wasn't the problem either. – Matthew Walker May 29 '19 at 21:51
  • I guess if I change `$request` to `$request[0]` it fixed the problem though I'm not sure why I needed to do that? – Matthew Walker May 29 '19 at 22:06
  • Request is an array of objects. the first object holds the Username, the second holds opening. You could simplify that structure if you have control over the input file. – Jerry May 29 '19 at 22:15

1 Answers1

1

I think you were expecting JSON data that looked like this:

{
    "Username": "redphyre@gmail.com",
    "opening": "Friends and Family..."
}

Where you have a single object with all the expected properties.

What you are actually getting, however, is this:

[
    { "Username": "redphyre@gmail.com" },
    { "opening": "Friends and Family..." }
]

That creates an array of objects, each with only one property, which is not nearly as easy to work with. To convert the data to a single object with multiple properties, you can loop though your result set:

$responseData = new stdClass();

foreach ($response as $propertyObject) {
    $properties = get_object_vars($propertyObject);

    // Just in case some objects have more than one property after all
    foreach($properties as $name => $value) {
        $responseData->$name = $value;
    }
}

That will copy the individual properties of the objects in the response array into a single object.

Jerry
  • 3,391
  • 1
  • 19
  • 28