Вы находитесь на странице: 1из 21

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

The Mobile Bundle Get $500+ Worth of Premium Files for Just $20 Advertise Here

How to Build a Shopping Cart using CodeIgniter and jQuery


Philo Hermans on Dec 14th 2009 with 203 Comments and 0 Reactions

Tutorial Details
Topic:CodeIgniter, jQuery Difficulty: Intermediate Estimated Completion Time: 30 minutes

Final Product What You'll Be Creating

CodeIgniter is an open source PHP web application framework with a lot of features. Recently, thanks to the latest update, a new feature was added to this framework, called the Cart Class. In this tutorial, were going to take advantage of this new class, and write a shopping cart system, with a touch of jQuery added in.

What is CodeIgniter?
1 de 21 24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

CodeIgniter is a powerful PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit to create full-featured web applications. If youre a developer who lives in the real world of shared hosting accounts and clients with deadlines, and if youre tired of ponderously large and thoroughly undocumented frameworks, CodeIgniter is for you!

In this tutorial, I am using the latest stable version of CodeIgniter, V1.7.2. This tutorial requires you to have some modest knowledge of CodeIgniter and the MVC pattern. The following tutorials will get you started right away! Everything You Need to Get Started by Ben Haines CodeIgniter From Scratch: Day 1 by Jeffrey Way

Resources
Before we can start, we need to download CodeIgniter and jQuery. Click here to download CodeIgniter, and here to download jQuery. Alternatively, you can reference jQuery via Googles CDN: http://ajax.googleapis.com/ajax/libs/jquery /1.3.2/jquery.min.js type=text/javascript

Folder Structure
Before we start coding, I would like to create a solid structure for our application. I prefer to move the application folder out of the system folder; this is not required, but it makes the update process easier in the future. The final folder we need to create before beginning is the assets folder; this is where I store my images, Javascript, CSS and other assets. Lets take a look at the final folder structure:

2 de 21

24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

Inside the folder assets/js, we place our jquery-1.3.2.min.js file, and an empty file called core.js. In this file, we will write our JavaScript. And one more thing remains: we need to create our stylesheet. So create a new file in assets/css called core.css.

Database
We are going to retrieve our products from the database; so lets go to PHPMyAdmin and create a table called CI_Cart.

And for those of you who want to copy and paste, the SQL Code view plaincopy to clipboardprint? 1. 2. 3. 4. 5. 6. 7. CREATE TABLE `products` ( `id` int(128) NOT NULL auto_increment, `name` varchar(128) NOT NULL, `price` varchar(32) NOT NULL, `image` varchar(128) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Now, lets insert some data into this table:

3 de 21

24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

Again for those who would prefer to copy and paste: view plaincopy to clipboardprint? 1. INSERT INTO `products` VALUES(1, 'MacBook Pro', '1199', 'macbookpro.jpg'); 2. INSERT INTO `products` VALUES(2, 'MacBook Air', '1499', 'macbookair.jpg'); 3. INSERT INTO `products` VALUES(3, 'MacBook', '999', 'macbook.jpg'); Theres everything that needs to be done for our database in this tutorial.

Step 1: Application Config


Before we can start using CodeIgniter, we have to setup our configuration. Open application/config/config.php, and change the following: view plaincopy to clipboardprint? 1. $config['base_url'] = "http://example.com"; Replace http://example.com with the url to your installation. Next, look for Global XSS Filtering located near the bottom of the config.php file. view plaincopy to clipboardprint? 1. $config['global_xss_filtering'] = FALSE; Lets change FALSE to TRUE, in order to make this filter active when GET, POST or COOKIE data is encountered. Next, open application/config/database.php and enter your database information. view plaincopy to clipboardprint? 1. 2. 3. 4. $db['default']['hostname'] = "localhost"; $db['default']['username'] = "root"; $db['default']['password'] = "root"; $db['default']['database'] = "CI_Cart";

4 de 21

24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

5. $db['default']['dbdriver'] = "mysql"; Next, open application/config/routes.php and change the default controller to cart: view plaincopy to clipboardprint? 1. $route['default_controller'] = "cart"; Now when someone visits the url to your application, the cart class will be loaded automatically. We have one more file to edit, so open application/config/autoload.php and autoload the following components: view plaincopy to clipboardprint? 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. /* | ------------------------------------------------------------------| Auto-load Libraries | ------------------------------------------------------------------| These are the classes located in the system/libraries folder | or in your system/application/libraries folder. | | Prototype: | | $autoload['libraries'] = array('database', 'session', 'xmlrpc'); */ $autoload['libraries'] = array('cart', 'database'); /* | ------------------------------------------------------------------| Auto-load Helper Files | ------------------------------------------------------------------| Prototype: | | $autoload['helper'] = array('url', 'file'); */ $autoload['helper'] = array('url', 'form');

Libraries database Allows your application to connect with a database and makes the database class available. cart Allows you to access the shopping cart class, more information. Helpers url The url library allows you to access different methods to create and retrieve links, more information form This library helps us with creating form. For more information

Step 2: Cart Controller


We changed our default controller to cart, but this controller does not yet exist. So, create a new file called application/controllers/cart.php and add the default controller structure. view plaincopy to clipboardprint? 1. 2. 3. 4. 5. 6. 7. 8. 9. <?php class Cart extends Controller { // Our Cart class extends the Controller class function Cart() { parent::Controller(); // We define the the Controller class is the parent. } } /* End of file cart.php */ /* Location: ./application/controllers/cart.php */

5 de 21

24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

Now, lets create our index function. This will run automatically when the class cart is requested. view plaincopy to clipboardprint? 1. function index() 2. { 3. $data['products'] = $this->cart_model->retrieve_products(); // Retrieve an array with all products 4. } So what happens here? Well you will notice that we assigned the output of our cart_model to a variable called $data['products']. If we refresh our page, we will get an error, because we havent made our cart_model yet.

Step 3: Creating our Model


What is a Model?

Models are PHP classes that are designed to work with information in your database. For example, lets say you use CodeIgniter to manage a blog. You might have a model class that contains functions to insert, update, and retrieve your blog data. Models are created in the following folder: application/models/; so lets create our model file called cart_model.php, and make a few edits. view plaincopy to clipboardprint? 1. <?php 2. class Cart_model extends Model { // Our Cart_model class extends the Model class 3. } 4. /* End of file cart_model.php */ 5. /* Location: ./application/models/cart_model.php */ Its as simple as that; we have created our model. Its important that you extend your Cart_model with Model in order to make it work properly. Remember when we called our model in the index() function of our cart controller? We called a function called retrieve_products, so lets create that! view plaincopy to clipboardprint? 1. <?php 2. class Cart_model extends Model { // Our Cart_model class extends the Model class 3. // Function to retrieve an array with all product information 4. function retrieve_products(){ 5. $query = $this->db->get('products'); // Select the table products 6. return $query->result_array(); // Return the results in a array. 7. } 8. } 9. /* End of file cart_model.php */ 10. /* Location: ./application/models/cart_model.php */ Refresh the page, and see what happens:

We created our model, and called the function retrieve_products from our cart controller, but we forgot to load it.
6 de 21 24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

There are different methods on how to load a model, but in this tutorial Im going to call it in the construct function, or in this case, the cart function located at the top of our controllers/cart.php file. view plaincopy to clipboardprint? 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. <?php class Cart extends Controller { // Our Cart class extends the Controller class function Cart() { parent::Controller(); // We define the the Controller class is the parent. $this->load->model('cart_model'); // Load our cart model for our entire class } } /* End of file cart.php */ /* Location: ./application/controllers/cart.php */

Now, test it out by printing the array. view plaincopy to clipboardprint? 1. function index() 2. { 3. $data['products'] = $this->cart_model->retrieve_products(); // Retrieve an array with all products 4. print_r($data['products']); // Print out the array to see if it works (Remove this line when done testing) 5. } If everything processed correct, you should see the following in your browser.
Array ( [0] => Array ( [id] => 1 [name] => MacBook Pro [price] => 1199 [image] => mac [1] => Array ( [id] => 2 [name] => MacBook Air [price] => 1499 [image] => mac [2] => Array ( [id] => 3 [name] => MacBook [price] => 999 [image] => macbook.

Now that we have retrieved our content, we have to display it using a view!

Step 4: Creating our View


What is a View?

A view is simply a web page, or a page fragment, like a header, footer, sidebar, etc. In fact, views can flexibly be embedded within other views (within other views, etc., etc.) if you need this type of hierarchy. Views are never called directly, they must be loaded by a controller. Remember that in an MVC framework, the Controller acts as the traffic cop, so it is responsible for fetching a particular view. Open the folder application/views, and create a new file called index.php. view plaincopy to clipboardprint? 1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1strict.dtd"> 2. <html xml:lang="en-us" xmlns="http://www.w3.org/1999/xhtml"> 3. <head> 4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5. <title>CodeIgniter Shopping Cart</title> 6. <link href="<?php echo base_url(); ?>assets/css/core.css" media="screen" rel="stylesheet" type="text/css" /> 7. <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.3.2.min.js"></script> 8. <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/core.js"></script> 9. </head> 10. <body> 11. <div id="wrap">

7 de 21

24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

12. <?php $this->view($content); ?> 13. </div> 14. </body> 15. </html> This is going to be our core template. As you can see, we load our jQuery and our stylesheet. Because we loaded the url helper, base_url(); will return the url to our application. We are also loading a view that contains a variable called $content. This allows us to dynamically load content. If we define that $content is demo, the view views/demo.php will be loaded for example.

Step 5: Sending Data to our View


In Step 3, we prepared our index function, and retrieved all products from the database, but we havent sent the data to a view yet; so open
/application/controllers/cart.php

view plaincopy to clipboardprint? 1. function index() 2. { 3. $data['products'] = $this->cart_model->retrieve_products(); // Retrieve an array with all products 4. $data['content'] = 'cart/products'; // Select our view file that will display our products 5. $this->load->view('index', $data); // Display the page with the above defined content 6. } As you can see, we have set the variable $content to cart/products. We havent made this view yet, so lets do that now. Create a new file in application/views/cart and call it products.php. Within this file, well display the data that we received from our cart model. We are going to use an unsorted list to display our products. view plaincopy to clipboardprint? 1. <ul class="products"> 2. <li></li> 3. </ul> Because the product data is being returned in a array, we have to use foreach in order to display all products view plaincopy to clipboardprint? 1. <ul class="products"> 2. <?php foreach($products as $p): ?> 3. <li> 4. </li> 5. <?php endforeach;?> 6. </ul> Now that weve started a foreach loop, we can start displaying the product data. view plaincopy to clipboardprint? 1. <ul class="products"> 2. <?php foreach($products as $p): ?> 3. <li> 4. <h3><?php echo $p['name']; ?></h3> 5. <img src="<?php echo base_url(); ?>assets/img/products/<?php echo $p['image']; ?>" alt="" /> 6. <small>&euro;<?php echo $p['price']; ?></small> 7. <?php echo form_open('cart/add_cart_item'); ?> 8. <fieldset> 9. <label>Quantity</label>

8 de 21

24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

10. <?php echo form_input('quantity', '1', 'maxlength="2"'); ?> 11. <?php echo form_hidden('product_id', $p['id']); ?> 12. <?php echo form_submit('add', 'Add'); ?> 13. </fieldset> 14. <?php echo form_close(); ?> 15. </li> 16. <?php endforeach;?> 17. </ul> Lets break the above code down into consumable pieces. view plaincopy to clipboardprint? 1. <h3><?php echo $p['name']; ?></h3> We display the product name in an H3 tag. view plaincopy to clipboardprint? 1. <img src="<?php echo base_url(); ?>assets/img/products/<?php echo $p['image']; ?>" alt="" /> Here, we use the base_url function to retrieve the url to our application, and then access the folder assets/img. Then we request the product image from the database. view plaincopy to clipboardprint? 1. <small>&euro;<?php echo $p['price']; ?></small> We display the product price retrieved from the database, and wrapp it within small tags. view plaincopy to clipboardprint? 1. <?php echo form_open('cart/add_cart_item'); ?> 2. <fieldset> We use the form helper to create the form opening tag, and set the action to cart/add_cart_item. view plaincopy to clipboardprint? 1. 2. 3. 4. <label>Quantity</label> <?php echo form_input('quantity', '1', 'maxlength="2"'); ?> <?php echo form_hidden('product_id', $p['id']); ?> <?php echo form_submit('add', 'Add'); ?>

This is the part where the user can define the quantity of items he/she wants. We use the form helper again to create an input field with the name quantity and set the default value to 1. We also pass through some extra data in this case, we set the maxlength to 2. We also placed a hidden field again using the form helper and named it product_id. Next, we have the submit button, with the name add and the default value Add. view plaincopy to clipboardprint? 1. </fieldset> 2. lt;?php echo form_close(); ?> Finally, we close our fieldset, and the form. Now lets add some CSS! view plaincopy to clipboardprint? 1. body{ 2. font-family: "Lucida Sans"; 3. font-size: 12px; 4. } 5. #wrap{ 6. width: 1024px;
9 de 21 24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

7. } 8. ul.products{ 9. list-style-type: none; 10. width: 525px; 11. margin: 0; 12. padding: 0; 13. } 14. ul.products li{ 15. background: #eeeeee; border: 1px solid #d3d3d3; 16. 17. padding: 5px; 18. width: 150px; 19. text-align: center; 20. float: left; 21. margin-right: 10px; 22. } 23. ul.products h3{ 24. margin: 0; 25. padding: 0px 0px 5px 0px; 26. font-size: 14px; 27. } 28. ul.products small{ 29. display: block; 30. } 31. ul.products form fieldset{ 32. border: 0px; 33. } 34. ul.products form label{ 35. font-size: 12px; 36. } 37. ul.products form input[type=text]{ 38. width: 18px; 39. background: #FFF; 40. border: 1px solid #d3d3d3; 41. } Ive added three images to assets/img/products, which correspond to the names from the database.

Step 6: Adding a Product to the Cart


We want to add products to the cart using jQuery, but we also want it to work for users who dont have JavaScript enabled. Lets dive into our JavaScript file, assets/js/core.js, and start with the jQuery opening tags: view plaincopy to clipboardprint? 1. $(document).ready(function() { 2. /*place jQuery actions here*/ 3. }); Because CodeIgniter uses a mod_rewrite kind of url index.php/cart, we are going to define a var with the url to our application: view plaincopy to clipboardprint?
10 de 21 24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

1. $(document).ready(function() { 2. /*place jQuery actions here*/ 3. var link = "/tutorials/CodeIgniter_Shopping_Cart /demo/index.php/"; // Url to your application (including index.php/) 4. }); Dont forget to change it accordingly to your situation. Next, we want to see if any form is being submitted. We can use the jQuery submit function to do just that. view plaincopy to clipboardprint? 1. $(document).ready(function() { 2. /*place jQuery actions here*/ 3. var link = "/tutorials/CodeIgniter_Shopping_Cart /demo/index.php/"; // Url to your application (including index.php/) 4. $("ul.products form").submit(function() { 5. return false; // Stop the browser of loading the page defined in the form "action" parameter. 6. }); 7. }); Before we can send the data using jQuery, we have to get the values that we have to send. So we use the jQuery find function to find the fields we need, and retrieve their values. view plaincopy to clipboardprint? 1. $(document).ready(function() { 2. /*place jQuery actions here*/ 3. var link = "/tutorials/CodeIgniter_Shopping_Cart /demo/index.php/"; // Url to your application (including index.php/) 4. $("ul.products form").submit(function() { 5. // Get the product ID and the quantity 6. var id = $(this).find('input[name=product_id]').val(); 7. var qty = $(this).find('input[name=quantity]').val(); 8. return false; // Stop the browser of loading the page defined in the form "action" parameter. 9. }); 10. }); If youd like to test it out, add an alert and lets see what happens. view plaincopy to clipboardprint? 1. $(document).ready(function() { 2. /*place jQuery actions here*/ 3. var link = "/tutorials/CodeIgniter_Shopping_Cart /demo/index.php/"; // Url to your application (including index.php/) 4. $("ul.products form").submit(function() { 5. // Get the product ID and the quantity 6. var id = $(this).find('input[name=product_id]').val(); 7. var qty = $(this).find('input[name=quantity]').val(); 8. alert('ID:' + id + '\n\rQTY:' + qty); 9. return false; // Stop the browser of loading the page defined in the form "action" parameter. 10. }); 11. });

So that works fine! This means we can start sending these values using jQuery Post.
11 de 21 24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

view plaincopy to clipboardprint? 1. $(document).ready(function() { 2. /*place jQuery actions here*/ 3. var link = "/tutorials/CodeIgniter_Shopping_Cart /demo/index.php/"; // Url to your application (including index.php/) 4. $("ul.products form").submit(function() { 5. // Get the product ID and the quantity 6. var id = $(this).find('input[name=product_id]').val(); 7. var qty = $(this).find('input[name=quantity]').val(); 8. $.post(link + "cart/add_cart_item", { product_id: id, quantity: qty, ajax: '1' }, 9. function(data){ 10. // Interact with returned data 11. }); 12. return false; // Stop the browser of loading the page defined in the form "action" parameter. 13. }); 14. }); In the code above, we post data to our cart controller and request the function add_cart_item. This an example of the posted data:
product_id: 3 quantity: 1 ajax: 1

Besides the product data, you can see that we also send through a variable called ajax, with the value 1. We can use this to check if the user has JavaScript enabled or not. Because when its disabled, only the product_id and the quantity will be posted. Before we can start interacting with the data returned from our post, we have to create the function that returns the data. Open application/controllers/cart.php and add a function named add_cart_item view plaincopy to clipboardprint? 1. function add_cart_item(){ 2. if($this->cart_model->validate_add_cart_item() == TRUE){ 3. // Check if user has javascript enabled 4. if($this->input->post('ajax') != '1'){ 5. redirect('cart'); // If javascript is not enabled, reload the page with new data 6. }else{ 7. echo 'true'; // If javascript is enabled, return true, so the cart gets updated 8. } 9. } 10. } In the code above, we start our function add_cart_item. Next, we use an if statment to check if the cart_model function called validate_add_cart_item() returns true. We still have to create that function, but what this does in the end, is check if the product exists, and then adds it to the cart. Well go over this a bit more shortly.

12 de 21

24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

You can now see why weve added the ajax value in the jQuery Post. If no ajax is posted, it means the user has disabled JavaScript which means we must reload the page so that the user sees a refreshed cart. If ajax is posted, we return the value true, so jQuery knows that everything processed correctly. Lets move on and create the validate_add_cart_item() function! Open application/models/cart_model.php view plaincopy to clipboardprint? 1. // Add an item to the cart 2. function validate_add_cart_item(){ 3. // Validate posted data, and then add the item! 4. } First we are going to assign the posted data to a local variable. view plaincopy to clipboardprint? 1. // Add an item to the cart 2. function validate_add_cart_item(){ 3. $id = $this->input->post('product_id'); // Assign posted product_id to $id 4. $cty = $this->input->post('quantity'); // Assign posted quantity to $cty 5. } Now, its time to validate the posted data, and see if the product exists. view plaincopy to clipboardprint? 1. // Add an item to the cart 2. function validate_add_cart_item(){ 3. $id = $this->input->post('product_id'); // Assign posted product_id to $id 4. $cty = $this->input->post('quantity'); // Assign posted quantity to $cty 5. $this->db->where('id', $id); // Select where id matches the posted id 6. $query = $this->db->get('products', 1); // Select the products where a match is found and limit the query by 1 7. } We create a query, and request to return 1 result where the posted id matches the id within the database. view plaincopy to clipboardprint? 1. // Add an item to the cart 2. function validate_add_cart_item(){ 3. $id = $this->input->post('product_id'); // Assign posted product_id to $id 4. $cty = $this->input->post('quantity'); // Assign posted quantity to $cty 5. $this->db->where('id', $id); // Select where id matches the posted id 6. $query = $this->db->get('products', 1); // Select the products where a match is found and limit the query by 1 7. // Check if a row has matched our product id 8. if($query->num_rows > 0){ 9. // We have a match! 10. }else{ 11. // Nothing found! Return FALSE! 12. return FALSE; 13. } 14. } If nothing is found, we return false. If a match is found, we add the item to cart. view plaincopy to clipboardprint? 1. // Add an item to the cart 2. function validate_add_cart_item(){ 3. $id = $this->input->post('product_id'); // Assign posted product_id to $id 4. $cty = $this->input->post('quantity'); // Assign posted quantity to $cty 5. $this->db->where('id', $id); // Select where id matches the posted id 6. $query = $this->db->get('products', 1); // Select the products where a match is found and limit the query by 1
13 de 21 24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. }

// Check if a row has matched our product id if($query->num_rows > 0){ // We have a match! foreach ($query->result() as $row) { // Create an array with product information $data = array( 'id' => $id, 'qty' => $cty, 'price' => $row->price, 'name' => $row->name ); // Add the data to the cart using the insert function that is available because we loaded the cart library $this->cart->insert($data); return TRUE; // Finally return TRUE } }else{ // Nothing found! Return FALSE! return FALSE; }

Before we can use jQuery to reload the cart, we have to create the cart list.

Step 7: Creating the Cart View


First, lets open application/views/index.php and add a div for our cart. view plaincopy to clipboardprint? 1. <div id="wrap"> 2. <?php $this->view($content); ?> 3. <div class="cart_list"> 4. <h3>Your shopping cart</h3> 5. <div id="cart_content"> 6. <?php echo $this->view('cart/cart.php'); ?> 7. </div> 8. </div> 9. </div> Above, we created a div called cart_list, and, inside, a div with the id cart_content. Now inside the div cart_content, we are going to load another view called cart.php. Create a new file in application/views/cart/, and name it cart.php. Add the following code: view plaincopy to clipboardprint? 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. <?php if(!$this->cart->contents()): echo 'You don\'t have any items yet.'; else: ?> <?php echo form_open('cart/update_cart'); ?> <table width="100%" cellpadding="0" cellspacing="0"> <thead> <tr> <td>Qty</td> <td>Item Description</td> <td>Item Price</td> <td>Sub-Total</td> </tr> </thead>

14 de 21

24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42.

<tbody> <?php $i = 1; ?> <?php foreach($this->cart->contents() as $items): ?> <?php echo form_hidden('rowid[]', $items['rowid']); ?> <tr <?php if($i&1){ echo 'class="alt"'; }?>> <td> <?php echo form_input(array('name' => 'qty[]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); ?> </td> <td><?php echo $items['name']; ?></td> <td>&euro;<?php echo $this->cart->format_number($items['price']); ?></td> <td>&euro;<?php echo $this->cart->format_number($items['subtotal']); ?></td> </tr> <?php $i++; ?> <?php endforeach; ?> <tr> <td</td> <td></td> <td><strong>Total</strong></td> <td>&euro;<?php echo $this->cart->format_number($this->cart->total()); ?></td> </tr> </tbody> </table> <p><?php echo form_submit('', 'Update your Cart'); echo anchor('cart/empty_cart', 'Empty Cart', 'class="empty"');?></p> <p><small>If the quantity is set to zero, the item will be removed from the cart.</small></p> <?php echo form_close(); endif; ?>

Thats quite some code; lets break it down into different parts. view plaincopy to clipboardprint? 1. <?php if(!$this->cart->contents()): 2. echo 'You don\'t have any items yet.'; 3. else: 4. ?> We use an if statment to check if the cart contains any content. If the cart does not have any content, we display the message You dont have any items yet. If the cart is not empty, we will run the rest of the code. view plaincopy to clipboardprint? 1. <?php echo form_open('cart/update_cart'); ?> 2. <table width="100%" cellpadding="0" cellspacing="0"> 3. <thead> 4. <tr> 5. <td>Qty</td> 6. <td>Item Description</td> 7. <td>Item Price</td> 8. <td>Sub-Total</td> 9. </tr> 10. </thead> Next, we create our form open tag using the form helper, and set the action parameter to cart/update_cart. We also created a table with a tableheading, and added the Quantity, Item Description, Item Price, and Sub-Total fields. view plaincopy to clipboardprint?

1. <tbody> 2. <?php $i = 1; // Keep track of the amount of loops ?> 3. <?php foreach($this->cart->contents() as $items): // We break the cart contents into parts ?> 4. <?php echo form_hidden('rowid[]', $items['rowid']); // We added an hidden field which contains a unique id in array format, t
15 de 21 24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

5. <tr <?php if($i&1){ echo 'class="alt"'; // If $i is odd, we add the class "alt" in order to change the background color }?>> 6. <td> 7. <?php echo form_input(array('name' => 'qty[]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); // Here we crea 8. </td> 9. <td><?php echo $items['name']; // Display the item name ?></td> 10. <td>&euro;<?php echo $this->cart->format_number($items['price']); // Display the item price ?></td> 11. <td>&euro;<?php echo $this->cart->format_number($items['subtotal']); // Display subtotal ?></td> 12. </tr> 13. <?php $i++; // Add 1 to $i ?> 14. <?php endforeach; // End the foreach ?> 15. <tr> 16. <td</td> 17. <td></td> 18. <td><strong>Total</strong></td> 19. <td>&euro;<?php echo $this->cart->format_number($this->cart->total()); // Display the total amount ?></td> 20. </tr> 21. </tbody>
What is a Row ID?

The row ID is a unique identifier that is generated by the cart code when an item is added to the cart. The reason a unique ID is created is so that identical products with different options can be managed by the cart. For example, lets imagine that someone buys two identical t-shirts (same product ID), but in different sizes. The product ID (and other attributes) will be identical for both sizes because its the same shirt. The only difference will be the size. The cart must therefore have a means of identifying this difference so that the two sizes of shirts can be managed independently. It does so by creating a unique row ID based on the product ID and any options associated with it. view plaincopy to clipboardprint? 1. 2. 3. 4. 5. 6. 7. </table> <p><?php echo form_submit('', 'Update your Cart'); echo anchor('cart/empty_cart', 'Empty Cart', 'class="empty"');?></p> <p><small>If the quantity is set to zero, the item will be removed from the cart.</small></p> <?php echo form_close(); endif; ?>

Finally, we close the table and create a link using the anchor function to cart/emtpy_cart. We will create the empty cart function shortly. Refresh the page and take a look:

We havent told jQuery to update the shopping cart when Add is pressed. But we can test it out using FireBug. Click Add, and review what happens:

As you can see, jQuery posts the data to cart/add_cart_item; now lets see what the response is.

16 de 21

24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

TRUE is returned, so refresh your page, and you should have an item in your shopping cart.

Now that this works, lets move on with jQuery, and refresh the cart when an item is added to the cart.

Step 8: Refreshing Cart


Remember that we ended up with: view plaincopy to clipboardprint? 1. $(document).ready(function() { 2. /*place jQuery actions here*/ 3. var link = "/tutorials/CodeIgniter_Shopping_Cart /demo/index.php/"; // Url to your application (including index.php/) 4. $("ul.products form").submit(function() { 5. // Get the product ID and the quantity 6. var id = $(this).find('input[name=product_id]').val(); 7. var qty = $(this).find('input[name=quantity]').val(); 8. $.post(link + "cart/add_cart_item", { product_id: id, quantity: qty, ajax: '1' }, 9. function(data){ 10. // Interact with returned data 11. }); 12. return false; // Stop the browser of loading the page defined in the form "action" parameter. 13. }); 14. }); Now its time to interact with the returned data, in this case true or false. view plaincopy to clipboardprint? 1. $.post(link + "cart/add_cart_item", { product_id: id, quantity: qty, ajax: '1' }, 2. function(data){ 3. if(data == 'true'){ 4. }else{ 5. alert("Product does not exist"); 6. } 7. }); By using an if statment, we can refresh the cart if true is returned, or give an alert when the product the user is trying to add does not exist. view plaincopy to clipboardprint? 1. $.post(link + "cart/add_cart_item", { product_id: id, quantity: qty, ajax: '1' },

17 de 21

24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

2. function(data){ 3. if(data == 'true'){ 4. $.get(link + "cart/show_cart", function(cart){ // Get the contents of the url cart/show_cart 5. $("#cart_content").html(cart); // Replace the information in the div #cart_content with the retrieved data 6. }); 7. }else{ 8. alert("Product does not exist"); 9. } 10. }); When true has been returned, we use jQuerys get, to load the url cart/show_cart, and we replace the div #cart_content with data returned by that url. But, you might notice that the function show_cart does not exist yet; lets create that now by opening our controller
application/controllers/cart.php

This is a very easy solution. We just have to return the contents of the cart, create the function, and return the view
views/cart/cart.php

view plaincopy to clipboardprint? 1. function show_cart(){ 2. $this->load->view('cart/cart'); 3. } Refresh the page, and try to add another item. jQuery should add it without reloading the page. (Unless you have JavaScript disabled, of course.)

Step 9: Update Cart


Just a few steps left! When you have items in your cart, press update, and take a look what is actually being posted:

As you can see, the rowid is unique for every item in the shopping cart. Were going to use these ids to check which item must be updated. Open application/controllers/cart.php, and add the function update_cart. view plaincopy to clipboardprint? 1. function update_cart(){ 2. $this->cart_model->validate_update_cart();
18 de 21 24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

3. redirect('cart'); 4. } Again, we use a model to handle the data. After thats done, we refresh the users page. Open application/models /cart_model.php, and create a new function called validate_update_cart. view plaincopy to clipboardprint? 1. // Updated the shopping cart 2. function validate_update_cart(){ 3. // Get the total number of items in cart 4. $total = $this->cart->total_items(); 5. // Retrieve the posted information 6. $item = $this->input->post('rowid'); 7. $qty = $this->input->post('qty'); 8. // Cycle true all items and update them 9. for($i=0;$i < $total;$i++) 10. { 11. // Create an array with the products rowid's and quantities. 12. $data = array( 13. 'rowid' => $item[$i], 14. 'qty' => $qty[$i] 15. ); 16. // Update the cart with the new information 17. $this->cart->update($data); 18. } 19. } As you can see, we first assign the total amount of items in our cart to a local variable called $total. Next, we assign the posted rowids and quantities to local variables as well. We use for to cycle through all items until $i equals $total this makes sure all items are updated. When cycling through the posted items, we create an array with the posted rowid and the quantity. When the array is created, we update this information using the cart library function called update. Give it a try and see if the items are being updated!

Step 10: Empty Cart


Our final step! We have to create a function to empty our cart. Open application/controllers/cart.php again and create a function called empty_cart. view plaincopy to clipboardprint?

19 de 21

24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

1. function empty_cart(){ 2. $this->cart->destroy(); // Destroy all cart data 3. redirect('cart'); // Refresh te page 4. } Add some jQuery to that! Open assets/js/core.js and write the following: view plaincopy to clipboardprint? 1. $(".empty").live("click", function(){ 2. $.get(link + "cart/empty_cart", function(){ 3. $.get(link + "cart/show_cart", function(cart){ 4. $("#cart_content").html(cart); 5. }); 6. }); 7. return false; 8. }); Our Emtpy Cart link has a class called .empty; so we attach a click function to it with no problems. You might notice that we are using the jQuery live function. We have to use this in order to make it work. If we left it out, and you add an item to the cart, and then press empty cart, it wont work. After the link is clicked, we use the same code that is in the update cart function. First, we fetch the empty_cart url so our cart will be empty, and then we simply fetch the new cart content, and place that content into our #cart_content div.

Done!

I hope you enjoyed this tutorial! If you did, please let us know within the comments! Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for the best web development tutorials on the web. Ready Ready to take your skills to the next level, and start profiting from your scripts and components? Check out our sister marketplace, CodeCanyon.

Like

137 people like this. Sign Up to see what your friends like.

Philo Hermans is philo01 on Codecanyon

20 de 21

24-01-2013 22:33

How to Build a Shopping Cart using CodeIgniter and jQuery | Nettuts+

http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using...

Tags: codeigniterecommercejQuery

By Philo Hermans
Hi there! My name is Philo from The Netherlands. I am a freelance web designer / developer and love to design and build websites and web applications. Ill try to write more high quality tutorials for nettuts.com soon! Follow me on Twitter | Themeforest or check out my website

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more

21 de 21

24-01-2013 22:33

Вам также может понравиться