I'm working on shopping cart. Now I need to pass the array of objects added into shopping cart which is stored in localStorage to php page in order to insert into database.
console.log(localStorage.getItem("shoppingCart"));
Above logs out, the following:
[{"name":"Banana","price":1.33,"count":5},{"name":"Apple","price":1.22,"count":5},{"name":"Shoe","price":22.33,"count":1}]
Now I'm trying to pass this JSON string to a php page called submit_cart.php and retrieve the string in php page correctly, how do I do that? Currently it's sending and receiving empty data.
$("#submit-cart").click(function(event){
console.log("****TEST LOG ***");
console.log(localStorage.getItem("shoppingCart"));
var data = localStorage.getItem("shoppingCart");
$.ajax({
type: "POST",
dataType: "json",
url: "submit_cart.php",
data: data,
success: function(data) {
console.log("******success******");
console.log(data);//this logs []
}
});
});
In submit_cart.php
<?php
$return = $_POST;
$return["json"] = json_encode($return);
$data = json_decode($return["json"], true);
echo json_encode($return["json"]);
?>
EDITED as suggested answer and it's working now:
$("#submit-cart").click(function(event){
console.log("****TEST LOG ***");
console.log(localStorage.getItem("shoppingCart"));
var data = localStorage.getItem("shoppingCart");
$.ajax({
type: "POST",
dataType: "json",
contentType: 'application/json',
url: "submit_cart.php",
data: data,
success: function(data) {
console.log("******success******");
console.log(data);//this logs []
}
});
});
In submit_cart.php
<?php
$_POST = json_decode(file_get_contents('php://input'),true);
print_r($_POST);
?>
print_r($_POST);at the top of your PHP script, so you can see what it contains. I am pretty sure doing ajson_encode()of all of the $_POST array is NOT what you want to do.json_encode($return);. removejson_encode($return);and check