user3790736
user3790736

Reputation: 1

PHP shows "{" or "[" for JSON Object Attributes sent via Angular $http

I've never seen this problem before, and I can't find the issue anywhere online. I'm using Angular to post form data to a PHP page. I'm using the file_get_contents() method of retrieving the POST data, which is a simple JSON object.

The problem arises with the data attributes - when I assign php vars to the data, they always have the value "{" or "[" (I echo'd and logged them). Any idea what could be causing this problem?

The relevant form declaration:

<form name="itemForm" ng-if="true" id="newItemForm" class="add-item" ng-submit="addItem(itemForm)">
            <input type="text" class="form-control data-entry"  ng-model="itemForm.itemType" placeholder="Type" ng-focus="true">

Here's my Angular function:

$scope.addItem = function(itemForm) {
        $http.post("../ajax/addItem.php", itemForm).success(function(data) {
            //console.data(JSON.stringify(itemForm));
            console.log(data);
            currItem = itemForm;
            itemsArr.push(angular.copy(itemForm));
            $scope.itemForm = defaultForm;
            getItem();
        });
    };

partial PHP:

<?php 

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

if($params){
    $item = $params["item"];
    $type = $item["itemType"];
    //get other parameters, insert into MySQL database

    echo json_encode(["type = " => $type]);
}
?>

Upvotes: 0

Views: 170

Answers (2)

elitechief21
elitechief21

Reputation: 3034

The file_get_contents function returns a string, so the $params variable is a string not an array. However, strings in php can be accessed in an array like fashion (except the key must be a number). In your code $item = $params["item"] should will give you a php warning and php will automatically assume an index of 0 since the key you gave was not a number. This is why you were getting { or [ when you echoed the data from php (because valid json is enclosed by {} or []).

To use $params as an array like you are trying to do you first need to do $params = json_decode($params). This will only work assuming you have a valid json string in the file you are reading from.

Upvotes: 1

Marc B
Marc B

Reputation: 360722

You're using string-based keys for your array. In Javascript terms, that has to be represented as an Object, which uses {} as the delimiters. Proper arrays, which use [], only accept numerical keys.

And note that type = as an array key is somewhat redundant. Why not just type?

Upvotes: 1

Related Questions