I am trying to send an array from php to javascript through ajax and am having some troubles.
My php array code looks something like this:
if($_REQUEST['action'] == 'miniCart'){
foreach($_SESSION['cart']['items'] as $item){
$message[$item['id']]['name'] = $item['name'];
$message[$item['id']]['price'] = number_format($item['price'], 2, '.', '');
$message[$item['id']]['qty'] = $item['count'];
}
$message = json_encode($message,true);
}
And this builds an array that looks something like this:
[2] =>
[name] => "Product 1"
[price] => "$15.00"
[qty] => "2"
[1] =>
[name] => "Product 2"
[price] => "$15.00"
[qty] => "3"
My JS code looks something like this:
var miniCart = function () {
$(".tester").on("click", function(event) {
var action = 'miniCart';
$.ajax({
type: "POST",
url: "cart/cart.php",
data:"action=" + action + "&ajax=true",
success: function(string){
var obj = jQuery.parseJSON(string);
alert( obj.name);
}});
});
}
My Json that is sent from php to JS looks like this:
{“2”:{“name”:”Product 1”,”price”:”15.00”,”qty”:”3”},”1”:{“name”:”Product 2”,”Price”:”15.00”,”qty”:”3”}}
I understand that this wont work, if someone can help finish this so that I can construct another array on the JS side that would be most helpful. My problem is that I can't parse them out correctly. I have tried many variations of JSON parsing but I think the "2" in the beginning is throwing it off. The item ID will never always be changing depending upon the order.
Perhaps I'm trying to engineer this incorrectly. I ultimately want to use these variables to build a shopping cart table.
Please assist.
Thank you kindly.