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.twitter.com/NeilBradley Neil Bradley

    Man, I’ve been waiting for someone to create a tute about the new Cart class. Excellent work. Can’t wait to get rolling with this.

  • http://zck.in Zachary

    There are several minor, but important issues with this tutorial.

    You should never call from $_POST (or $this->input->post()) in a model, that’s bad MVC, but pass local vars in. That makes for un-reuseable code.

    There are a few instances where css classes should be id’s. Never use a class, if the block won’t be reused (such as in ) There will only every be one cart list, so use an ID

  • http://www.webstuffshare.com Hidayat Sagita

    I think we can use

    rather than

    to minimize php code in our Views file.
    CMIIW

    • http://www.webstuffshare.com Hidayat Sagita

      Ups sorry i just type the php script i think it will change to the html code (htmlentities) (admin please help me :D )

      I think we can use

      rather than

      to minimize php code in our Views file.
      CMIIW

      • http://www.webstuffshare.com Hidayat Sagita

        Sorry,

        I think we can use
        <?= echo form_submit(’add’, ‘Add’); ?>
        rather than
        <?php echo form_submit(’add’, ‘Add’); ?>
        to minimize php code in our Views file.
        CMIIW

      • http://www.webstuffshare.com Hidayat Sagita

        Sorry,
        I think we can use
        <?=form_submit(’add’, ‘Add’); ?>
        rather than
        <?php echo form_submit(’add’, ‘Add’); ?>
        to minimize php code in our Views file.
        CMIIW

      • http://twitter.com/HO_BA Ihab

        Using short php tags isn’t always a good thing as they may be disabled by default

        so using is always a good practice

        http://www.php.net/manual/en/language.basic-syntax.phpmode.php

  • http://twitter.com/HO_BA Ihab

    Really very nice tutorial , Philo

    but , I think something wrong here in view/cart/cart.php line 21

    <tr >

    I don’t think

    if($i&1){ echo 'class="alt"'; }

    will do what it should do.

    more interesting way to do so is using alternator() in string helper

    http://codeigniter.com/user_guide/helpers/string_helper.html

    credit to Derek Allard

    http://derekallard.com/blog/post/alternating-comment-styles/

    Ah , also I can’t understand why in views/index.php you use

    view($content); ?>

    instead of using

    load->view($content); ?>

    Is there a reason for that ?

  • http://www.adslviettel.com viettel

    That a good tutorial!

  • moiz

    there is nothing as simple as codeigniter .. and a combination of CI with Jquery is smashing !!!
    i dont remember any mojor project that i’ve done that does not use Jquery since the past 2 yrs now ..

    anyone not using a Javascript library is just living in the pre historic times yet .. ppl get cracking on Jquery, its awesome !!

    hey dude, show us some kind of demo of this entire explanation..

  • Raoul

    My developper will be happy :p

    But thanks for the time you spend on writting this well commented tut.

    Best,
    R.

  • http://twitter.com/HO_BA ihab

    Sorry about misunderstanding. But this is the first time I know about if($i&1) trick, really cool trick

    but I blame Philo for not explaining what & operator is and how it work . I think it was typo or something :oops:

    anyhow this link on stack overflow helped me http://stackoverflow.com/questions/600202/understanding-phps-operator

    • http://www.philohermans.com Philo Hermans
      Author

      My bad, I forgot to explain, it’s quite a long tutorial, so sometimes I forget to explain things when I’m writing everything down.

      Sorry for the inconvenience.

  • http://matt-bridges.com Matt B

    I have been looking forward to a tutorial on the cart library in CodeIgniter. I myself have not had an opportunity to use it in any way, but I will definitely turn here for reference when I do (but their documentation is fantastic!).

    Great tut!

  • Aaron

    @nick….15th Dec
    Pull your head in….. not everyone writes and speaks English as there first Language. No need to be so critical. Get a life….

    Thanks for the great tutorial Phil…. good work

    @ Jeff W…. whens the next Ci Series Coming out? Please :)

  • exi

    great tutorial, but i’m not seeing the download link for the tutorial files – is it just me? I see the jQuery and Codeigniter links, but not a demo or source link anywhere.

  • http://www.webmastervideoschool.com Alex

    Here is a video tutorial I made about PHP shopping cart.

    http://www.webmastervideoschool.com/blog_item.php?id=3

    Hope you will find it useful.

    Alex

  • http://theadhamian.wordpress.com/ Adham

    thanks maw !

  • http://blog.foodadda.com Rohit

    hey Philo
    nice article man
    amazing!!!!!

  • Daniel Olsson

    Hi

    First i’d like to say thanks :)

    Second:
    Does anyone know why the swedish letters ÅÄÖ åäö mess the cart up ?
    When there is for example a ‘å’ in the name the product simply won’t be added to the cart.

    I’d appreciate some pushes in the right direction.

    Thanks in advance and happy new year.

    • Daniel

      I found the solution, It wasn’t very hard at all.
      the cart class filters the products name.
      And the ÅÄÖ wasn’t okay by the cart class.

      I had to tinker a bit with the if statement in order to bypass the check. (For me having a namefilter isn’t important at all.)

  • Dimitar Danailov

    http://82.103.68.218/NetTutsPlusTutorials/How%20to%20Build%20a%20Shopping%20Cart%20using%20CodeIgniter%20and%20jQuery/CodeIgniter_1.7.2/

    First Question

    Example :
    I already have row in my shopping cart MacBook with Quantity = 1 ,when add new MackBook with Quantity = 2.No add new row in my shopping card ,just update row Mackbook with Quantity =2.

    Second Question
    In core.js why no have code for update button ?
    I no see result when i submit my shoping cart ,only refresh the page.

  • Akash

    Hi,
    Its super but I could not found the core.css file. please explain a bit how can I get it

    Thanks
    akash

  • AJ Koop

    Great tutorial. What is, in your opinion, the best way to start processing payments from a shopping cart like this?

    • AJ Koop

      Probably Magento, right?

  • bruno borges

    Nice tutorial, but products with the character like ‘(‘ ‘)’, for example: ‘hot dog (46.301)’, doesn’t works. Everybody knows why this hapend?

  • Sharea

    Amazing!

    QUESTION:
    Is there any way i can add catogories and or use checkboxes?

    Thanks!

  • http://www.eng-mmf.com M.M.F

    Very Nice :)
    thanks

  • Suborn

    Dear Philo Hermans

    Kindly can you explain below line.

    var link = “/tutorials/CodeIgniter_Shopping_Cart/demo/index.php/”; // Url to your application (including index.php/)

    I do not used index.php file. So what code i used instead of abode code.

  • raju

    A PHP Error was encountered
    Severity: Notice

    Message: Undefined property: CI_Loader::$cart

    Filename: cart/cart.php

    Line Number: 1

    Fatal error: Call to a member function contents() on a non-object in C:\Program Files\xampp\htdocs\sample_project\application\views\cart\cart.php on line 1

    Please help me what can i do at this moment.
    i can not understand what type this error and how can i solve it?

  • cal

    What a brilliant post. Outstanding, one of the best CI tutes I’ve seen. Bravo and many, many thanks.

  • http://jeric.net23.net/ci/welcome/index jeric realubit

    Tnxs! just finished this tutorial and its great! good job!

  • mack

    thanks excellent job

  • aftriska

    hi..
    i’ve tried this tutorial but i couldn’t make things work.
    everytime I tried to add a product it was always return the “product does not exist” alert.
    But if I disabled the javascript, it went well.
    I’m still trying to find out what’s wrong..
    Maybe somebody can help me?

  • http://armansyah.web.id/ Armand Macintosh

    Take a look at these two lines:

    var id = $(this).find(‘input[name=product_id]‘).val();
    var qty = $(this).find(‘input[name=quantity]‘).val();

    you defined the cart list in a loop, so ‘product_id’ and ‘quantity’ identifiers will be duplicated on the form. jQuery will only get the first input value at that form and you’ll get a problem.

  • http://www.ferienwohnung-prag.info wiyono

    hallo,
    Thank you for tutorial,
    i have questions, how when i would like to make direct in hosting not in localhost, how i make table for sql?

    can you help me pleasseeee…

    Best Regard
    Wiyono
    Indonesia

  • http://www.casadosnegocios.com/estoque/index.php/estoque/entrada Brayan

    Hey, I need help :D

    I can’t add products that names have slashes.. they are not added to the cart

    click on my name to see the page.. click on ‘Adicionar’ to add a product.. and select one that have slashes.. and then Add. Nothing happens:@

    someone knows why ?

    thank you n sorry for the bad english

  • http://None Jaro

    Hey Everyone,

    I would like to add a product into the shopping cart and be able to see the image in the shopping. Can someone send me the code how to implement that into the code?

    Or an explanation on how to do it?

    Thanks

    Jaro

  • http://coderfrombd.com Md Sajjadul Farooque Robin

    A very nice tutorial. I am looking for something like that.

    Thanks

  • http:www.centralindiatourism.com imran

    i didn’t get the line

    var link = “/tutorials/CodeIgniter_Shopping_Cart/demo/index.php/”; // Url to your application (including index.php/)

    in core.js file

    please help

  • http://codeignitersusah.blogspot.com Erick Sitorus

    Thanks for your tutorial, very helpfull for me as a beginner…

    your tutorial look neater n easier to understand… well look…

  • walterbyrd

    Stuck on step 5, can not get the images to print. The images are there, they are named correctly. The URL is correct. Everything else works.

    CodeIgniter 1.7.2.
    Ubuntu 10.04
    Firefox 3.6.8

  • walterbyrd

    Nevermind, I got it. I left the “http://” of the “localhost” in the config.php file.

    I had:

    $config['base_url'] = “localhost/ci”;

    Instead of:

    $config['base_url'] = “http://localhost/ci”;

  • http://www.slowtrick.com Jelle

    Heey Perfect Tut,

    I learned some new good practises with CI. Small improvement I like, is when you click on add to cart the second time it will update the quantity (just like @Dimitar Danailov). Too bad the CI Cart doesn’t work this way yet.

    Here the update on the model class for this! (cart_model.php)
    ———————————————

    // Add an item to the cart
    function validate_add_cart_item(){

    $id = $this->input->post(‘product_id’); // Assign posted product_id to $id
    $qty = $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 been found?
    if($query->num_rows > 0){

    //Find existing product?
    foreach($this->cart->contents() as $item) {
    //print_r($item);
    if($item['id'] == $id) {

    $data = array(
    ‘rowid’ => $item['rowid'],
    ‘qty’ => $item['qty'] + $qty
    );

    $this->cart->update($data);
    return TRUE;
    }
    }

    //New Product
    $row = $query->row();
    $data = array(
    ‘id’ => $id,
    ‘qty’ => $qty,
    ‘price’ => $row->price,
    ‘name’ => $row->name
    );

    $this->cart->insert($data);

    return TRUE;

    // Nothing found! Return FALSE!
    }else{
    return FALSE;
    }
    }

    • http://weareduo.co.uk Colin

      Nice addition – was thinking this myself, you just saved me the time thinking about it!

    • Andy

      Thanks for that =D

  • Mike

    Followed the instructions verbatim – got to step 8 and the products are not being added to the cart. Very frustrating.

  • Mike

    I should give you more information:

    Using WAMP, and the Firebug console show’s the correct POST with a response of true – the GET response shows “You don’t have any items yet”. Nothing happens when I refresh the page or turn JavaScript off.

  • Mike

    Problem solved – I wasn’t following the directions completely verbatim – I had changed the product names to include the price – I was using the a “£” in the name field – I removed that and everything is working as it should.

  • Mike

    The tutorial appears to be incomplete – after updating the cart the URL changes to index/cart, and then when you try to add any more cards there is a 404 in the POST.

  • http://binarysolo.tv Naz

    The empty cart button doesn’t work, I had to remove the ‘class=”empty”‘ before it cleared everything.

    </

  • mirws

    Thanks.. this is very usefull..
    But I think the tutorial is not stop here… there should be another tutorial for this topic
    and I’m waiting for it…

  • JCTron

    I get this error and I don’t Know why.

    [07-Sep-2010 09:34:08] PHP Fatal error: Call to undefined method cart_model::validate_add_cart_item() in C:\wamp\www\CodeIgniterShoppingCart\application\controllers\cart.php on line 19

    Can anybody help me?

  • http://www.panaceatek.com Anil Kumar Bohare

    “We are going to retrieve our products from the database; so let’s go to PHPMyAdmin and create a table called CI_Cart.”
    Above line is written in this tutorial, There is one written mistake that is “CI_Cart is not table it should be database” because table name is “products”

  • http://weareduo.co.uk colin

    Hey, I know this was wrote a long time ago, but I just went through it and got it all working – was just wondering what the point is in using the javascript? doesn’t it all work through codeigniter alone?

  • xavier emerson

    hi… man….
    You have done fantastic work …
    Lots of thankz…
    I’m just beginner in codeigniter ….
    This stuff help me a lot…
    Thankz again…

  • http://www.1firstweb.com happyber

    Thank you. This very good.

  • horlvd

    hi admin, i’m finding it hard to read the tutorial above because of it’s format. please help. thanks.

  • denroy robyn

    great work! is there any way jquery can be used to delete a single line item