Tuesday, April 9, 2013

jQuery shopping cart

Your manager told you to put shopping cart into an existing site? And told you to use jQuery and AJAX in order to prevent page reload as customer click on products in catalog? And add a couple of effects?

I'll give you basic instructions on this. Keep in mind that creating shopping cart from scratch is very difficult so I'll show you how to implement this without database - with two products and sessions, but the code is easy to modify to fit your development needs.

In this tutorial I'll use session in order to transfer data between web pages and AJAX calls. So make sure that it is enabled in php.ini file and while testing check the length of session in minutes. Don't forget to delete cookie PHPSESSID on localhost when testing.

First we load file elem.php into browser:
<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery and PHP shopping cart</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    // Add a product to shopping cart using jQuery AJAX feature
 $('.rr').click(function(){
  var target = $(this).attr("id");
    $.ajax({
    type: 'POST',
    url: 'cart.php',
    data: { id: target },
    error: function() {
       alert('Error!');
    },
    success: function(data) {
       $('#cart').html(data);
                   // add jQuery effects
       $('#wrap').fadeTo(1000, 0.25);
       $('#wrap').fadeTo(1000,1);
    }
   });
 });

 // Clear shopping cart
 $('.clear').click(function(){
  var target = $(this).attr("id");
    $.ajax({
    type: 'POST',
    url: 'clear.php',
    data: { clear: 'yes' },
    error: function() {
       alert('Error!');
    },
    success: function(data) {
       $('#cart').html(data);
    }
   });
 });
});
</script>
<style>
.wrap{
font-size:120%;
border:double;
line-height: 2.5;
padding:3px;
}
</style>
</head>
<body>
<h1>Shop without refreshing whole page</h1>
<h3>Our products</h3>
<a id="10" class="rr" href="#">Buy Monitor</a> Price $120<br/>
<a id="20" class="rr" href="#">Buy Keyboard</a> Price $5<br/>
<span class="wrap" id="wrap">Your cart has $<span id="cart">0</span>, and your session id is: <strong><?php echo session_id(); ?></strong></span>
<a id="checkout" class="checkout" href="checkout.php">Procede to checkout...</a><br/>
<a id="clear" class="clear" href="#">Clear cart</a><br/>
</body>
</html>
When you click on product links amount of in your cart is getting bigger and there's no refreshing of the whole web page, thanks to file cart.php:
<?php
session_start();
$id = $_POST['id'];
if($id == 10) $_SESSION['total'] = $_SESSION['total'] + 120;
if($id == 20) $_SESSION['total'] = $_SESSION['total'] + 5;
echo $_SESSION['total'];
?>
In production environment you'll get data such as price and product ID from a database or XML file.
When you want to empty your cart click on "clear cart" link it will activate another AJAX call in file clear.php:
<?php
session_start();
session_unset();
session_destroy();
$_SESSION = array();
echo "0";
?>
and when you click on Proceed to checkout you will be redirected to checkout.php:
<?php
session_start();
echo '<h1>Your shopping cart</h1>';
if (empty($_SESSION['total'])) die('You have an empty shoping cart.');
echo "You bought $".$_SESSION['total']." of goods and your session ID is:".session_id();
?>
On that page in production environment you should list products, total amount and implement PayPal or other internet payment solutions.
We can see how it looks like:

As you can see this solution is easy to customize.

No comments:

Post a Comment