Ajax shopping cart, built using PHP + Prototype

Ajax is getting popular these days. Many would wanna convert their traditional shopping carts for their online stores into Ajax-driven, which needent page refresh. A tutorial example has been posted on PHPBuilder how to use Prototype on the JavaScript client side, to make ajax remote calls and PHP on the server to store the cart items.

On the client side, a few functions need to be done as follows using Prototype. Of course, be sure that you include the prototype.js in between your <head></head> tags

<script src=”prototype.js” type=”text/javascript”></script>

The main function of JavaScript that uses Prototype to send the remote ajax call (sending the task and the item no parameters to the managecart.php via AJAX) is the manageCart, with an additional function to report error as follows:

<script type=”text/javascript” language=”JavaScript”>
function manageCart(task, item)
  var url = ‘managecart.php’;
  var params = ‘task=’ + task + ‘&item=’ + item;
  var ajax = new Ajax.Updater(
    {success: ‘cartResult’},
    {method: ‘get’, parameters: params, onFailure: reportError});

function reportError(request) {
  $F(‘cartResult’) = “An error occurred”;

On the page where the shopping cart is being displayed is a DIV that has the id “cartResult” as follows:

<div id=”cartResult”></div>
iPod Leather Case<br />
<a href=”#” onclick=”manageCart(‘add’,1)”;>Add this item to Cart</a>

Brando USB 4-port hub
<a href=”#” onclick=”manageCart(‘add’,3)”;>Add this item to Cart</a>

<a href=”viewcart.php”>View your shopping cart</a>

And on the server side, the managecart.php which does simple task, and being passed with two parameters, which the first one is the task which determines whether it shall add a new item to the cart or delete an item. And the second parameter is the item no that uniquely identifies each item that is stored in the database. And the items will be stored on the instance of cart.class.php, which items are stored in array and then being stored in PHP session.



$items = $_SESSION["cart"];

$cart = new Shopping_Cart($items);

// Retrieve the parameters
$task = $_GET['task'];
$item = $_GET['item'];

if ($task == “add”) {
   $_SESSION["cart"] = $cart->getCart();
   echo “item added!”;
} else {
   echo “item deleted!”;

And another PHP page, viewcart.php that shows the cart’s content, as follows:

Your Shopping Cart contains:

Articles : Source 1, Source 2

Enter your email address to subscribe our newsletter or feed for FREE:

Delivered by FeedBurner

Bookmark with:

[Delicious]    [Digg]    [Reddit]    [Facebook]    [StumbleUpon]

0 Responses to “Ajax shopping cart, built using PHP + Prototype”

  1. No Comments

Leave a Reply

You must login to post a comment.