1. Code
  2. PHP

How to Build a Shopping Cart using CodeIgniter and jQuery

Scroll to top
Read Time: 24 min

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!


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


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

Now, let's insert some data into this table:

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

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:

Replace with the url to your installation. Next, look for Global XSS Filtering located near the bottom of the config.php file.

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.

Next, open application/config/routes.php and change the default controller to "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:


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


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.

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

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.

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!

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.

Now, test it out by printing the array.

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

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.

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

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.

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

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

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

We display the product name in an H3 tag.

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.

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

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

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

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

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:

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:

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.

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.

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

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

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"

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

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

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

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

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

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.

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:

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

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.

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.

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.

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:

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

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.

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

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.

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.

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.

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

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.


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.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.