How to Build a Shopping Cart using CodeIgniter and jQuery

How to Build a Shopping Cart using CodeIgniter and jQuery

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, we’re going to take advantage of this new class, and write a shopping cart system, with a touch of jQuery added in.


What is CodeIgniter?

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 you’re a developer who lives in the real world of shared hosting accounts and clients
with deadlines, and if you’re 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!


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 Google’s 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.
Let’s take a look at the final folder structure:

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 let’s go to PHPMyAdmin and create a table called CI_Cart.

And for those of you who want to copy and paste, the SQL Code…

	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, let’s insert some data into this table:

Again – for those who would prefer to copy and paste:

	INSERT INTO `products` VALUES(1, 'MacBook Pro', '1199', 'macbookpro.jpg');
	INSERT INTO `products` VALUES(2, 'MacBook Air', '1499', 'macbookair.jpg');
	INSERT INTO `products` VALUES(3, 'MacBook', '999', 'macbook.jpg');
	

There’s 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:

	$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.

	$config['global_xss_filtering'] = FALSE;
	

Let’s 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.

	$db['default']['hostname'] = "localhost";
	$db['default']['username'] = "root";
	$db['default']['password'] = "root";
	$db['default']['database'] = "CI_Cart";
	$db['default']['dbdriver'] = "mysql";
	

Next, open application/config/routes.php and change the default controller to “cart”:

	$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:

		/*
		| -------------------------------------------------------------------
		|  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


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.

	<?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 */
	

Now, let’s create our index function. This will run automatically when the class cart is requested.

		function index()
		{
		    $data['products'] = $this->cart_model->retrieve_products(); // Retrieve an array with all products
		}	
	

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 haven’t 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, let’s 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 let’s create our model file called cart_model.php, and make a few edits.

	<?php 

		class Cart_model extends Model { // Our Cart_model class extends the Model class
		
		}
		
	/* End of file cart_model.php */
	/* Location: ./application/models/cart_model.php */
	

It’s as simple as that; we have created our model. It’s 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 let’s create that!

	<?php 

		class Cart_model extends Model { // Our Cart_model class extends the Model class
			
			// Function to retrieve an array with all product information
			function retrieve_products(){
				$query = $this->db->get('products'); // Select the table products
				return $query->result_array(); // Return the results in a array.
			}			
		
		}
		
	/* End of file cart_model.php */
	/* 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.
There are different methods on how to load a model, but in this tutorial I’m 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.

	<?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.

		function index()
		{
		    $data['products'] = $this->cart_model->retrieve_products(); // Retrieve an array with all products
		    print_r($data['products']); // Print out the array to see if it works (Remove this line when done testing)
		}	
	

If everything processed correct, you should see the following in your browser.

		Array ( [0] => Array ( [id] => 1 [name] => MacBook Pro [price] => 1199 [image] => macbookpro.jpg ) 
		        [1] => Array ( [id] => 2 [name] => MacBook Air [price] => 1499 [image] => macbookair.jpg ) 
		        [2] => Array ( [id] => 3 [name] => MacBook [price] => 999 [image] => macbook.jpg ) )
	

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.

		<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
		<html xml:lang="en-us" xmlns="http://www.w3.org/1999/xhtml">
		<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>CodeIgniter Shopping Cart</title>
		
		<link href="<?php echo base_url(); ?>assets/css/core.css" media="screen" rel="stylesheet" type="text/css" />
		
		<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.3.2.min.js"></script>
		<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/core.js"></script>
		</head>
		<body>
		
		<div id="wrap">
		
			<?php $this->view($content); ?>
			
		</div>
		
		</body>
		</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 haven’t sent the data to a view yet; so open
/application/controllers/cart.php

		function index()
		{
		    $data['products'] = $this->cart_model->retrieve_products(); // Retrieve an array with all products
			
			$data['content'] = 'cart/products'; // Select our view file that will display our products
			$this->load->view('index', $data); // Display the page with the above defined content
		}	
	

As you can see, we have set the variable $content to ‘cart/products.’ We haven’t made this view yet, so let’s do that now.

Create a new file in application/views/cart and call it products.php. Within this file, we’ll display the data that we received from our cart model. We are going to
use an unsorted list to display our products.

	<ul class="products">
		<li></li>
	</ul>
	

Because the product data is being returned in a array, we have to use foreach in order to display all products

	<ul class="products">
		<?php foreach($products as $p): ?>
		<li>
		</li>
		<?php endforeach;?>
	</ul>
	

Now that we’ve started a foreach loop, we can start displaying the product data.

	<ul class="products">
		<?php foreach($products as $p): ?>
		<li>
			<h3><?php echo $p['name']; ?></h3>
			<img src="<?php echo base_url(); ?>assets/img/products/<?php echo $p['image']; ?>" alt="" />
			<small>&euro;<?php echo $p['price']; ?></small>
			<?php echo form_open('cart/add_cart_item'); ?>
				<fieldset>
					<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'); ?>
				</fieldset>
			<?php echo form_close(); ?>
		</li>
		<?php endforeach;?>
	</ul>
	

Let’s break the above code down into consumable pieces.

	<h3><?php echo $p['name']; ?></h3>
	

We display the product name in an H3 tag.

	<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.

	<small>&euro;<?php echo $p['price']; ?></small>
	

We display the product price retrieved from the database, and wrapp it within small tags.

			<?php echo form_open('cart/add_cart_item'); ?>
				<fieldset>	
	

We use the form helper to create the form opening tag, and set the action to “cart/add_cart_item”.

					<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.”

				</fieldset>
			<?php echo form_close(); ?>
	

Finally, we close our fieldset, and the form. Now let’s add some CSS!

	body{
		font-family: "Lucida Sans";
		font-size: 12px;
	}
	
	#wrap{
		width: 1024px;
	}
	
	ul.products{
		list-style-type: none;
		width: 525px;
		margin: 0;
		padding: 0;
	}
	
		ul.products li{
			background: #eeeeee;
			border: 1px solid #d3d3d3;
			padding: 5px;
			width: 150px;
			text-align: center;
			float: left;
			margin-right: 10px;
		}
	
		ul.products h3{
			margin: 0;
			padding: 0px 0px 5px 0px;
			font-size: 14px;
		}
		
		ul.products small{
			display: block;
		}
		
		ul.products form fieldset{
			border: 0px;
		}
		
		ul.products form label{
			font-size: 12px;
		}
		
		ul.products form input[type=text]{
			width: 18px;
			background: #FFF;
			border: 1px solid #d3d3d3;
		}
	

I’ve 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 don’t have JavaScript enabled. Let’s dive into our JavaScript file, assets/js/core.js, and start with the jQuery opening tags:

	$(document).ready(function() { 
	/*place jQuery actions here*/ 
	
	});
	

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:

	$(document).ready(function() { 
		/*place jQuery actions here*/ 
		var link = "/tutorials/CodeIgniter_Shopping_Cart/demo/index.php/"; // Url to your application (including index.php/)
	
	});
	

Don’t 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.

	$(document).ready(function() { 
		/*place jQuery actions here*/ 
		var link = "/tutorials/CodeIgniter_Shopping_Cart/demo/index.php/"; // Url to your application (including index.php/)
	
		$("ul.products form").submit(function() {
	
			return false; // Stop the browser of loading the page defined in the form "action" parameter.
		});
	
	});
	

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.

	$(document).ready(function() { 
		/*place jQuery actions here*/ 
		var link = "/tutorials/CodeIgniter_Shopping_Cart/demo/index.php/"; // Url to your application (including index.php/)
	
		$("ul.products form").submit(function() {
			// Get the product ID and the quantity 
			var id = $(this).find('input[name=product_id]').val();
			var qty = $(this).find('input[name=quantity]').val();
			
			return false; // Stop the browser of loading the page defined in the form "action" parameter.
		});
	
	});
	

If you’d like to test it out, add an alert and let’s see what happens.

	$(document).ready(function() { 
		/*place jQuery actions here*/ 
		var link = "/tutorials/CodeIgniter_Shopping_Cart/demo/index.php/"; // Url to your application (including index.php/)
	
		$("ul.products form").submit(function() {
			// Get the product ID and the quantity 
			var id = $(this).find('input[name=product_id]').val();
			var qty = $(this).find('input[name=quantity]').val();
			
			alert('ID:' + id + '\n\rQTY:' + qty);
			
			return false; // Stop the browser of loading the page defined in the form "action" parameter.
		});
	
	});
	

So that works fine! This means we can start sending these values using jQuery Post.

	$(document).ready(function() { 
		/*place jQuery actions here*/ 
		var link = "/tutorials/CodeIgniter_Shopping_Cart/demo/index.php/"; // Url to your application (including index.php/)
	
		$("ul.products form").submit(function() {
			// Get the product ID and the quantity 
			var id = $(this).find('input[name=product_id]').val();
			var qty = $(this).find('input[name=quantity]').val();
			
		 	$.post(link + "cart/add_cart_item", { product_id: id, quantity: qty, ajax: '1' },
  				function(data){	
 		 			// Interact with returned data
 			 });
 			 
			return false; // Stop the browser of loading the page defined in the form "action" parameter.
		});
	
	});
	

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 it’s 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”

	function add_cart_item(){
		
		if($this->cart_model->validate_add_cart_item() == TRUE){
			
			// Check if user has javascript enabled
			if($this->input->post('ajax') != '1'){
				redirect('cart'); // If javascript is not enabled, reload the page with new data
			}else{
				echo 'true'; // If javascript is enabled, return true, so the cart gets updated
			}
		}
		
	}
	

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. We’ll go over this a bit more shortly.

You can now see why we’ve 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.

Let’s move on and create the validate_add_cart_item() function! Open application/models/cart_model.php

	// Add an item to the cart
	function validate_add_cart_item(){
		// Validate posted data, and then add the item!
	}
	

First we are going to assign the posted data to a local variable.

	// Add an item to the cart
	function validate_add_cart_item(){
		
		$id = $this->input->post('product_id'); // Assign posted product_id to $id
		$cty = $this->input->post('quantity'); // Assign posted quantity to $cty
		
	}
	

Now, it’s time to validate the posted data, and see if the product exists.

	// Add an item to the cart
	function validate_add_cart_item(){
		
		$id = $this->input->post('product_id'); // Assign posted product_id to $id
		$cty = $this->input->post('quantity'); // Assign posted quantity to $cty
		
		$this->db->where('id', $id); // Select where id matches the posted id
		$query = $this->db->get('products', 1); // Select the products where a match is found and limit the query by 1
		
	}
	

We create a query, and request to return 1 result where the posted id matches the id within the database.

	// Add an item to the cart
	function validate_add_cart_item(){
		
		$id = $this->input->post('product_id'); // Assign posted product_id to $id
		$cty = $this->input->post('quantity'); // Assign posted quantity to $cty
		
		$this->db->where('id', $id); // Select where id matches the posted id
		$query = $this->db->get('products', 1); // Select the products where a match is found and limit the query by 1
		
		// Check if a row has matched our product id
		if($query->num_rows > 0){
		
		// We have a match!
		
		}else{
			// Nothing found! Return FALSE!	
			return FALSE;
		}
	}
	

If nothing is found, we return false. If a match is found, we add the item to cart.

	// Add an item to the cart
	function validate_add_cart_item(){
		
		$id = $this->input->post('product_id'); // Assign posted product_id to $id
		$cty = $this->input->post('quantity'); // Assign posted quantity to $cty
		
		$this->db->where('id', $id); // Select where id matches the posted id
		$query = $this->db->get('products', 1); // Select the products where a match is found and limit the query by 1
		
		// 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, let’s open application/views/index.php and add a div for our cart.

	<div id="wrap">
	
		<?php $this->view($content); ?>
		
		<div class="cart_list">
			<h3>Your shopping cart</h3>
			<div id="cart_content">
				<?php echo $this->view('cart/cart.php'); ?>
			</div>
		</div>
	</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:

	<?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>
		<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;
	?>
	

That’s quite some code; let’s break it down into different parts.

	<?php if(!$this->cart->contents()):
		echo 'You don\'t have any items yet.';
	else:
	?>
	

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 don’t have any items yet.” If
the cart is not empty, we will run the rest of the code.

	<?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>
	

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.

		<tbody>
			<?php $i = 1; // Keep track of the amount of loops ?> 
			<?php foreach($this->cart->contents() as $items): // We break the cart contents into parts ?>
			
			<?php echo form_hidden('rowid[]', $items['rowid']); // We added an hidden field which contains a unique id in array format, this is needed in order to update ?>
			<tr <?php if($i&1){ echo 'class="alt"'; // If $i is odd, we add the class "alt" in order to change the background color }?>>
		  		<td>
		  			<?php echo form_input(array('name' => 'qty[]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); // Here we created an input field with the name qty[] this allows us to interact with it as an array when its posted.?>
		  		</td>
		  		
		  		<td><?php echo $items['name']; // Display the item name ?></td>
		  		
		  		<td>&euro;<?php echo $this->cart->format_number($items['price']); // Display the item price ?></td>
		  		<td>&euro;<?php echo $this->cart->format_number($items['subtotal']); // Display subtotal ?></td>
		  	</tr>
		  	
		  	<?php $i++; // Add 1 to $i ?>
			<?php endforeach; // End the foreach ?>
			
			<tr>
				<td</td>
	 		 	<td></td>
	 		 	<td><strong>Total</strong></td>
	 		 	<td>&euro;<?php echo $this->cart->format_number($this->cart->total()); // Display the total amount ?></td>
			</tr>
		</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, let’s 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 it’s 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.

	</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 let’s see what the response is.

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

Now that this works, let’s 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:

	$(document).ready(function() { 
		/*place jQuery actions here*/ 
		var link = "/tutorials/CodeIgniter_Shopping_Cart/demo/index.php/"; // Url to your application (including index.php/)
	
		$("ul.products form").submit(function() {
			// Get the product ID and the quantity 
			var id = $(this).find('input[name=product_id]').val();
			var qty = $(this).find('input[name=quantity]').val();
			
		 	$.post(link + "cart/add_cart_item", { product_id: id, quantity: qty, ajax: '1' },
  				function(data){	
 		 			// Interact with returned data
 			 });
 			 
			return false; // Stop the browser of loading the page defined in the form "action" parameter.
		});
	
	});
	

Now it’s time to interact with the returned data, in this case ‘true’ or ‘false.’

		 	$.post(link + "cart/add_cart_item", { product_id: id, quantity: qty, ajax: '1' },
  				function(data){	
 		 			
 		 			if(data == 'true'){
 		 			
 		 			}else{
 		 				alert("Product does not exist");
 		 			}
 			 });
	

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.

		 	$.post(link + "cart/add_cart_item", { product_id: id, quantity: qty, ajax: '1' },
  				function(data){	
 		 			
 		 			if(data == 'true'){
 		 			
    					$.get(link + "cart/show_cart", function(cart){ // Get the contents of the url cart/show_cart
  							$("#cart_content").html(cart); // Replace the information in the div #cart_content with the retrieved data
						}); 		 
										
 		 			}else{
 		 				alert("Product does not exist");
 		 			}
 			 });
	

When true has been returned, we use jQuery’s “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; let’s 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

	function show_cart(){
		$this->load->view('cart/cart');
	}
	

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. We’re going to use these ids to check which item must be updated.

Open application/controllers/cart.php, and add the function update_cart.

	function update_cart(){
		$this->cart_model->validate_update_cart();
		redirect('cart');
	}
	

Again, we use a model to handle the data. After that’s done, we refresh the user’s page. Open application/models/cart_model.php, and create a new
function called validate_update_cart.

	// Updated the shopping cart
	function validate_update_cart(){
		
		// Get the total number of items in cart
		$total = $this->cart->total_items();
		
		// Retrieve the posted information
		$item = $this->input->post('rowid');
	    $qty = $this->input->post('qty');

		// Cycle true all items and update them
		for($i=0;$i < $total;$i++)
		{
			// Create an array with the products rowid's and quantities. 
			$data = array(
               'rowid' => $item[$i],
               'qty'   => $qty[$i]
            );
            
            // Update the cart with the new information
			$this->cart->update($data);
		}

	}
	

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 rowid’s 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.

	function empty_cart(){
		$this->cart->destroy(); // Destroy all cart data
		redirect('cart'); // Refresh te page
	}
	

Add some jQuery to that! Open assets/js/core.js and write the following:

	$(".empty").live("click", function(){
    	$.get(link + "cart/empty_cart", function(){
    		$.get(link + "cart/show_cart", function(cart){
  				$("#cart_content").html(cart);
			});
		});
		
		return false;
    });
	

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 won’t 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!

Ready to take your skills to the next level, and start profiting from your scripts and components? Check out our sister marketplace, CodeCanyon.

CodeCanyon

Philo Hermans is philo01 on Codecanyon
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.24hourswebdesigner.com/ 24design

    Hey..! that was an interesting article for sure.
    Thank you very much for putting so much effort in this blog.
    It really means a lot to us. ^^

  • PeterGreffen

    First, let me say thanks for the excellent tutorials on Nettuts.

    The update_cart function in your controller is nice, but I didn’t like the redirect part.

    So, I made an update with Ajax, refreshing only the cart when updated. Thought I’d share it.

    function update_cart(){
    $this->cart_model->validate_update_cart();
    // redirect(‘cart’); <– remove this line, we are not going to redirect…
    }

    In my view (e.g. product details page) I load the cart view that contains only the little cart form

    Your shopping cart

    view(‘shop/view-cart.php’); ?>

    In the view-cart.php, I added this Ajax call:

    $(function(){
    $(“#upcart”).submit(function(){
    dataString = $(“#upcart”).serialize();

    $.ajax({
    type: “POST”,
    cache: false,
    url: ” + “cart/update_cart”,
    data: dataString,
    cache: false,
    success: function(msg){
    // HERE COMES THE RELOAD OF THE CART FORM
    $.get(” + “cart/show_cart”, function(cart){
    $(“#cart_content”).html(cart); // Replace the cart
    // SOME CANDY
    $(“#cart_message”).text(‘Updated!’);
    $(“#cart_message”).fadeOut(2000);
    });
    }

    });
    return false;
    });
    });

    The validate_update_cart and the other functions are the same as yours…

    Kind Regards,
    And thanks again!!
    Peter.

  • psifreak

    OK, I’m confused. Is this done in DW? I can’t find any of these references inside of Dreamweaver CS5, including a view setting that let’s me see the folder structure like that. If there’s supposed to be a compiler or debugger of any sort in those links, they’re both bunk.
    I’m actually using netbeans for the code/debug part, but how does this tie into CS5?

    • http://danaemc.com Danae

      Are you on a Mac?

  • Danae

    Great tutorial!

    Just wondering, is pressing “add” supposed to add onto the current amount in the cart? If so, mine isn’t working and I have to look over it again.

  • http://websitecenter.ca/ Iouri Goussev

    I’m not using code ignighter, but I ported this code to qcubed and it works well (qcubed is awesome, check it out).

  • http://josh-r.net/ Josh R.

    This tutorial is great!

    But how would we add a function to check out with Paypal or any other payment method?

  • http://mwindriyanto.web.id wahyu

    Thanks for the article. it will help me so much.
    Hopefully i can ask you in case i have problem implemented this.

  • http://- Alan Victor Lamb

    Hey Man, nice tutorial!

    Just a tip:

    Instead of using this:
    var link = “/tutorials/CodeIgniter_Shopping_Cart/demo/index.php/”;

    You could use:
    var link = “”;

    This CI function returns the same URL that is in your config file.
    So if you change the directory you don´t need to update your view files.

    []´s

  • http://webmarmun.com sasa

    Thanks!
    Really detailed and great tutorial!
    Keep up the good work!

  • http://tanimgt.blogspot.com tanim

    hey bro, i dont understand with… this file >> in config folder, $autoload['core'] = array(‘database’,'cart’);
    then, browser says… “unable to load cart class” . there is no cart class in the library. where i find that class. please please solve this. if you upload the full system folder that will be so helpful for novice like us. with regards.. >tanim<

  • http://www.crozwiserz.com appukuttan

    Awesom man! unbelievable effort! Can u just give a little deep analysis into form creation>?

  • ijaz ali

    excellent work by you great man…

  • Jade

    Hi, and thanks for a great tutorial.

    I just have one nagging question that I can’t find any information about.

    It seems this cart class is using sessions to create the customer’s cart, but I’m not very familiar with sessions.

    So, my question is this:

    How long will a session persist (in other words, how long will a customer’s cart continue to contain their items) AND, is there a way for me to reliably specify the time it should persist.

    My secondary question is:

    Is there an upper limit to the number of items this cart could reliably contain for a customer’s session?

    Explanation:

    I’m concerned that the project I’m considering this for will have customers spending 30-60 minutes adding potentially dozens (and dozens) of items to their cart. NOTE: it’s actually a rental company estimation request system I’m building.

    I realize my questions may be pretty noobish, but my mother always said the only dumb question is the one you don’t ask.

    Thanks in advance,
    Jade

  • nebraska69

    Sorry, noob here. I get the following error after step 3.

    Fatal error: Class ‘Controller’ not found in C:\wamp\www\ci\application\controllers\cart.php on line 3

    This is what I have in my application\controllers\cart.php file.

    <?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
    }

    function index()
    {
    $data['products'] = $this->cart_model->retrieve_products(); // Retrieve an array with all products
    print_r($data['products']); // Print out the array to see if it works (Remove this line when done testing)
    }

    }
    /* End of file cart.php */
    /* Location: ./application/controllers/cart.php */
    ?>

    Was following your excellent tutorial, but I am apprently doing something wrong somewhere.

    • http://johnregalado.com John

      What version of codeigniter are you using?

      If your using 2.0 make sure to update

      class Cart_model extends Model

      to

      class Cart_model extends CI_Model

      and

      class Cart extends Controller

      to

      class Cart extends CI_Controller

  • afif

    so how to submit the data on cart to database
    exampe : inserrt into sale_items
    ?

  • http://www.24hourswebdesign.com/ web design

    Outstanding piece of work.
    I am word less.
    Thank you for sharing

  • http://www.sutanaryan.com/ Ryan

    Great article, thanks for sharing

    but I didn’t like the way it added/updated to cart and change the URL to something like this http://www.example.com/codeigniter/index.php/cart

    so I have a little tweak here

    edit the redirect(‘cart’); in cart.php file under controller

    to redirect();, in 3 functions namely

    add_cart_item()
    update_cart()
    empty_cart()

    so when the time you add/update your cart, the URL only show the /index.php

    hope that help to other
    I am a codeigniter beginner ^_^

  • Alex

    Estimated Completion Time: 30 minutes? Really? I don’t know about you but this would take me 1-2 days to complete from scratch (without Codeigniter)…

  • http://bilallhr.weebly.com 1

    I’m getting msg that … You don’t have any items yet. :( by pessing add button TRUE is not posted… wht should i do ??

  • http://www.videolinkin.com Suhail

    Hi Philo Hermans,

    Its a great tutorial for Codeingitor lovers. Thanks a lot.

    Regards,
    Suhail

  • http://www.videolinkin.com Suhail

    Hi,

    First of all thanks for good tutorial, i have a problem here. Display items is working fine, but when i add to cart it doesn’t add anything in Shopping cart area. I am using this shopping cart in PyroCMS (Codeignitor).
    Upon investigating Codeignitor shopping cart uses table base session so i correct that in config file and create session table. But when i browse every time i see a new session id, and cart data is storing successfully. nothing to display in Shopping cart.

    • dheeraj

      hey what is that session table stuff plzzz explain me becouse when i m clicking on add button nothing is added to cart area :(

  • http://www.betterhelpworld.com Nisha

    Hi,

    Thanks for this article. How we can use this to process the orders in the shopping card? I means to integrate this system with a payment gateway.

  • http://www.namaz-saatleri.com kaan

    hi

  • http://yraykuffer.blogspot.com yraykuffer

    Which do you prefer, codeigniter or symfony? which of these is better to use?

  • Andy

    Great tutorial – thankyou =D

  • Jason

    This doesn’t work properly in IE 7 or 8. After first item is loaded to cart from ajax , each item after that is added to cart but the ajax doesn’t update the list to show it. Only if you press the manual update button will it appear. Any one notice same issues in IE?

  • http://devendraverma.posterous.com Devendra

    Very nice and detailed post … tks

  • http://www.elruinnou.co.cc erwin

    i don’t know if i’m doing wrong anywhere cause i used to have this apps working before, after long time i open again this apps, and the cart is going nothing. please help.. i use this for my task

  • monica

    thank you so much this blog very helpfull :)

  • Rhys

    Thanks heaps for this! :)

    Was having issues when updating the cart, as I was getting “undefined offset” notices and then “header already sent” problems (because of the redirect after updating?) from the validate_update_cart function in the cart_model, however when refreshed, the cart was actually updated.

    I think it’s because when updating the cart, “$total = $this->cart->total_items();” does not equal the number of rows in the cart. Changing this to “$total = count($item);” works for me, but I’m still learning codeigniter and PHP in general so I’m unsure if this is the best way to do it.

  • Eliza

    Increíble!!! Como caída del cielo….. ya tengo la mitad del trabajo hechoooo, graciaaaassssss !!!

  • Will

    I have the cart working perfectly. There is one question though. Others have asked it and I see no answers. After we have the products…. how do we submit them for payment. I added a checkout button but when I click on it…. it works like an update button.

  • Alle

    Cool, but how to cancel item using close button / x icon beside product, not set to zero

  • ketan

    hi it a nice……

  • how how

    yeah how to connect this to paypal visa or any other payment system?

  • http://www.harvirmatharu.com Harvey

    its all working apart from the add to cart. Any ideas?

  • tony

    In Step 5, you have this code:


    Let’s break the above code down into consumable pieces.
    view plaincopy to clipboardprint?

    We display the product name in an H3 tag.
    view plaincopy to clipboardprint?

    <img src="assets/img/products/” 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.”

    You do not explain very well that in the “img” folder there needs to be another folder called “products.” When I got through Step 7 and viewed the page, the pics were broken. If I am following step-by-step, this error is not explained and leads to 15 mins of backtracing to find the error.

  • Jeevith

    Thank you Sir…

  • Orestis

    I am trying to add your cart to a website that I am developing for online ordering system for food and am facing difficulties for this
    What actually to I have to put there?What is my URL?

    $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.

  • orestis

    Am getting this errror

    Fatal error: Call to undefined function base_url() in C:\wamp\www\Online-Ordering-System\demo\application\views\index.php on line 7 Call Stack #TimeMemoryFunctionLocation 10.0139373320{main}( )..\index.php:0

  • ALTELMA

    It’s goog tutorials for codeigniter. I looking tutorials like this….. OK Thanks alot

  • sangma

    Excellent tutor, how to complete the payment with paypal? Thanks a lot.

  • mgiota

    Great tutorial! But ubfortunately, I can’t add items to the cart. It keeps saying “You don’t have any items yet”. What am I doing wrong?

  • Ion

    Awesome. Great job. Thanks for your patience.

  • makara long

    This add to cart is good but when i add to cart one product first time 12 qty and then this product again 1 qty is not update to 13 it update to 1 anyone help?

  • http://zanala.com Omar Faruque

    This tutorial has empty cart option. When i click empty cart button then my cart is empty. But is it poosible like i want to delete one product item from cart.

    I need assistance.

  • vindika

    thank you so much this blog very help full…
    i am a fresher for codeigeniter. so
    but i have a problem in like this

    “Deprecated: Assigning the return value of new by reference is deprecated in C:\wamp\www\shopincart\system\codeigniter\Common.php on line 130″

    and

    “Deprecated: Assigning the return value of new by reference is deprecated in C:\wamp\www\shopincart\system\codeigniter\Common.php on line 136″
    pls help me…
    thanks….

  • Aux

    Hello in the Step 3: Creating our Model

    I see this:

    Fatal error: Class ‘Controller’ not found in C:\Program Files\Ampps\www\carrito\application\controllers\cart.php on line 3

    not yet arrived ti Step 4.

    help me please.

    • http://www.facebook.com/arkaindas Arkaprava Majumder

      Controller has been changed to CI_Controller in present version…

  • nilesh

    Thank you so much….

  • https://www.socialideas.mx alvaro

    Great tutorial! i got a question, how can i add more than 6 items to my shopping cart ?

    • Gabriel

      First set TRUE in .config

      $config['sess_use_database'] = TRUE;

      (line 238 )

      then ADD this table:

      CREATE TABLE IF NOT EXISTS `ci_sessions` (
      session_id varchar(40) DEFAULT ’0′ NOT NULL,
      ip_address varchar(16) DEFAULT ’0′ NOT NULL,
      user_agent varchar(50) NOT NULL,
      last_activity int(10) unsigned DEFAULT 0 NOT NULL,
      user_data text NOT NULL,
      PRIMARY KEY (session_id)
      );