Chapter 5: Building a Shopping Cart
118
function jsUpdateCart(){
var parameter_string = ‘’;
allNodes = document.getElementsByClassName(“process”);
for(i = 0; i < allNodes.length; i++) {
var tempid = allNodes[i].id;
var temp = new Array;
temp = tempid.split(“_”);
var real_id = temp[2];
var real_value = allNodes[i].value;
parameter_string += real_id +’:’+real_value+’,’;
}
var params = ‘ids=’+parameter_string;
var ajax = new Ajax.Updater(
‘ajax_msg’, ‘/welcome/ajax_cart’,
{method:’post’,parameters:params,onComplete:showMessage}
);
}
function showMessage(req){
$(‘ajax_msg’).innerHTML = req.responseText;
location.reload(true);
}
Creating the ajax_cart() Controller Function
The controller function ajax_cart() is incredibly simple. All it has to do is load the MOrders model
and then call a new function, updateCartAjax() , passing in as an argument the list of data supplied by
the jsUpdateCart() JavaScript function:
function ajax_cart(){
$this- > load- > model(‘MOrders’,’’,TRUE);
return $this- > MOrders- > updateCartAjax($this- > input- > post(‘ids’));
}
Expanding the MOrders Model
The final step in this process is to write a function called updateCartAjax() in the MOrders model.
This function steps through the provided list of IDs and counts and then updates the cart as needed.
If the count for a given product ID is 0, then remove it from the Shopping Cart array altogether. If the
count is the same as it was before for a given item, then don ’ t bother to change it. If it ’ s different, change
it. This will help you keep track of all changes as you go, so you can keep track of activity accurately.
When the process ends, it will return one of three messages. If no data were sent to the function
(unlikely, but possible), then it returns “ No records to update. ” If changes were made (i.e., the user raised
or lowered the number of items in the Shopping Cart), it returns the number of records that were
changed. If data were sent in, but no changes were made (i.e., the user simply hit the update button
without making any changes), it returns “ No changes detected. ”