Chapter 5: Building a Shopping Cart
123
This particular function will be a lot simpler than the jsUpdateCart() one. In fact, all it will do is
accept the incoming product ID and call a new controller function called ajax_cart_remove() :
function jsRemoveProduct(id){
var params = ‘id=’+id;
var ajax = new Ajax.Updater(
‘ajax_msg’,’/welcome/ajax_cart_remove’,
{method:’post’,parameters:params,onComplete:showMessage}
);
}
Notice that you ’ ll be reusing the showMessage() function from above.
Updating the Controller
All you have to do in the controller is add a new function called ajax_cart_remove(). This function
will simply call a function in the MOrders model that will remove the product represented by the
incoming product ID.
function ajax_cart_remove(){
return $this- > MOrders- > removeLineItem($this- > input- > post(‘id’));
}
Updating the Model
Finally, create a removeLineItem() function in the MOrders model. This function tries to delete the
incoming product ID from the Shopping Cart. If the Shopping Cart contains the product ID, it runs
unset() on that particular part of the Shopping Cart and then updates the totalprice. The last thing the
function does is report back whether a product was, indeed, removed.
function removeLineItem($id){
$totalprice = 0;
$cart = $_SESSION[‘cart’];
if (isset($cart[$id])){
unset($cart[$id]);
foreach ($cart as $id = > $product){
$totalprice += $product[‘price’] * $product[‘count’];
}
$_SESSION[‘totalprice’] = $totalprice;
$_SESSION[‘cart’] = $cart;
echo “Product removed.”;
}else{
echo “Product not in cart!”;
}
}
After loading all of this new code, run through the process of adding items to your Shopping Cart. If you
delete a product, you should see something similar to what is pictured in Figure 5 - 7.