Professional CodeIgniter

(singke) #1

Chapter 5: Building a Shopping Cart


119


function updateCartAjax($idlist){
$cart = $_SESSION[‘cart’];
//split idlist on comma first
$records = explode(‘,’,$idlist);
$updated = 0;
$totalprice = $_SESSION[‘totalprice’];
if (count($records)){
foreach ($records as $record){
if (strlen($record)){
//split each record on colon
$fields = explode(“:”,$record);
$id = $fields[0];
$ct = $fields[1];
if ($ct > 0 & & $ct != $cart[$id][‘count’]){
$cart[$id][‘count’] = $ct;
$updated++;
}elseif ($ct == 0){
unset($cart[$id]);
$updated++;
}
}
}

if ($updated){
$totalprice =0; //with changes, must reset this value!
foreach ($cart as $id = > $product){
$totalprice += $product[‘price’] * $product[‘count’];
}
$_SESSION[‘totalprice’] = $totalprice;

$_SESSION[‘cart’] =$cart;
echo $updated. “ records updated!”;
}else{
echo “No changes detected!”;
}
}else{
echo “No records to update!”;
}
}

Give it a try by changing a few items in the Shopping Cart and hitting Update. What you should see is
something similar to Figure 5 - 5.

Free download pdf