Passing an array of objects through the $http.post method in angular JS does not work

29 Views Asked by At

I aim to pass an array of objects from my main merchandise.php file to another process_cart.php file using the $http.post method. (Note that it's AngularJS, not Angular). I want to use a foreach loop to display the cart's contents on receiving the array.

This is what my function looks like. Cart is a JavaScript array.

$scope.processCart=function(){ 
    $http.post('process_cart.php', { cart: JSON.stringify(cart) })
    .then(function() {
    })
    .catch(function(error) {
        console.error(error);
    });
    }
      });

As for my process_cart.php file, it looks like this:

$cart = json_decode($_POST['cart'], true);

if (!empty($cart)) {
    foreach ($cart as $item) {
        $productId = $item['productId'];
        $quantity = $item['quantity'];

        echo "Product ID: $productId, Quantity: $quantity <br>";
    }
} else {
    echo "Cart is empty.";
}

The cart variable in the second file goes unrecognized. Where am I going wrong? Also, is there any other information I should share?

1

There are 1 best solutions below

3
talha masood On

instead of this:

$cart = json_decode($_POST['cart'], true);

try this:

$cart = file_get_contents("php://input");