Professional CodeIgniter

(singke) #1

Chapter 5: Building a Shopping Cart


117


Updating the template and shoppingcart Views


Once you ’ ve uploaded all the necessary files for the Scriptaculous framework, make a simple change to
your main template view, adding calls to those files so that they ’ re universally available:

< script type=”text/javascript” src=” < ?php echo
base_url();? > js/prototype.js” > < /script >

< script type=”text/javascript” src=” < ?php echo base_url();? > js/scriptaculous.js”
> < /script >

Furthermore, while you ’ re at it, add a call to a third file, one called customtools.js. For now, this file will
be empty, but it will contain all your custom JavaScript code.

< script type=”text/javascript” src=” < ?php echo base_url();? > js/customtools.js” >
< /script >

Next, you ’ re going to add an Update button to the shoppingcart view that calls a custom JavaScript
function called jsUpdateCart(). Just be sure to put this new button before the submit code:

echo “ < tr valign=’top’ > \n”;
echo “ < td colspan=’3’ > & nbsp; < /td > \n”;
echo “ < td > < input type=’button’ name=’update’ value=’update’
onClick=’javascript:jsUpdateCart()’/ > < /td > \n”;
echo “ < /tr > \n”;

There is one more thing you need to do with the shoppingcart view. At the very end of the file, add a
< div > tag with an ID of ajax_msg. As you ’ ll see in the next section, this is the < div > tag your Ajax
function will use to print status messages.

< div id=’ajax_msg’ > < /div >

Creating the Custom JavaScript Functions


Now open the /js/customtools.js file you created above and add two new JavaScript functions to it.

The first is jsUpdateCart() , which you ’ ll use to parse the Shopping Cart form and send information to
a custom controller function. In this function, use getElementsByClassName to grab all form elements
with the class name of process. Extract the ID assigned to each class, and then split that ID on the
underscore character ( _ ) to get the real numeric ID for the product. Finally, grab the value from the field
itself (i.e., how many of a particular product), and then send all of these data in a neat comma - and
colon - delimited bundle to the ajax_cart() controller function (which you ’ ll build momentarily).

The second function is showMessage() , which becomes the Ajax response. This is where any messages
or return values actually display in the browser. Notice that the function is sending the request output to
the ajax_msg div, then reloading the browser.
Free download pdf