i'm working on shopping cart. need pass array of objects added shopping cart stored in localstorage php page in order insert database.
console.log(localstorage.getitem("shoppingcart"));
above logs out, 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 pass json string php page called submit_cart.php , retrieve string in php page correctly, how do that? it's sending , 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 suggested answer , 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); ?>
on ajax request set content type json , on php side read json php://input
$.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 [] } });
$_post = json_decode(file_get_contents('php://input'),true); // use post usual
Comments
Post a Comment