Creating A Slick Ajaxed Shopping Cart With jQuery And PHP
It is a clear fact that Ajaxed interfaces, if not overused, eases using websites so much.
For an e-commerce website, this can mean a better shopping experience for customers where they can concentrate more on the products which may result in better sales.
This is a detailed tutorial which shows creating an unobtrusive Ajaxed shopping cart using jQuery & PHP and can guide you to Ajaxify any e-commerce software you may already be using or coding.
The main functions of the cart will be adding/removing items to the basket without the need of refreshing the page & displaying the actions with effects.
To try the demo or download the script:
The HTML
Rather than the formatting of the page, as you can design it however you prefer, we’ll be focusing on the vital parts which does all the tricks.
HTML For The Product’s Wrapper:
01.
<div
class
=
"productWrap"
>
02.
<div
class
=
"productImageWrap"
>
03.
<img src=
"images/product1.jpg"
alt=
"Product1"
/>
04.
</div>
05.
<div
class
=
"productNameWrap"
>
06.
Krups Coffee Maker
07.
</div>
08.
<div
class
=
"productPriceWrap"
>
09.
<div
class
=
"productPriceWrapLeft"
>
10.
$95
11.
</div>
12.
<div
class
=
"productPriceWrapRight"
>
13.
<a href=
"inc/functions.php?action=addToBasket&productID=1"
onClick=
"return false;"
>
14.
<img src=
"images/add-to-basket.gif"
alt=
"Add To Basket"
width=
"111"
height=
"32"
id=
"featuredProduct_1"
/>
15.
</a>
16.
</div>
17.
</div>
18.
</div>
The part we’ll focus is the contents inside <div>
which wraps the “add-to-basket” button.
The Highlights:
- a link with
onClick="return false;
value which means it won’t be active if JavaScript is active (to make the script unobtrusive) - add-to-basket image has an unique ID:
id="featuredProduct_1"
which we’ll use to understand the button of which product is clicked
HTML For The Basket:
01.
<div id=
"basketWrap"
>
02.
<div id=
"basketTitleWrap"
>
03.
Your Basket <span id=
"notificationsLoader"
></span>
04.
</div>
05.
<div id=
"basketItemsWrap"
>
06.
<ul>
07.
<li></li>
08.
<?php getBasket(); ?>
09.
</ul>
10.
</div>
11.
</div>
The Highlights:
- we have an empty
<span>
withid="notificationsLoader"
to show a loading image - we keep an empty div to be able to insert any data before/after them
- we call a PHP function:
<?php getBasket(); ?>
to get the basket data when the page is first loaded.
The JavaScript (jQuery)
We have 2 main jQuery functions:
Function For Adding To Basket:
01.
$(
".productPriceWrapRight a img"
).click(
function
() {
02.
var
productIDValSplitter = (
this
.id).split(
"_"
);
03.
var
productIDVal = productIDValSplitter[1];
04.
05.
$(
"#notificationsLoader"
).html(
'<img src="images/loader.gif">'
);
06.
07.
$.ajax({
08.
type:
"POST"
,
09.
url:
"inc/functions.php"
,
10.
data: { productID: productIDVal, action:
"addToBasket"
},
11.
success:
function
(theResponse) {
12.
13.
if
( $(
"#productID_"
+ productIDVal).length > 0){
14.
$(
"#productID_"
+ productIDVal).animate({ opacity: 0 }, 500,
function
() {
15.
$(
"#productID_"
+ productIDVal).before(theResponse).remove();
16.
});
17.
$(
"#productID_"
+ productIDVal).animate({ opacity: 0 }, 500);
18.
$(
"#productID_"
+ productIDVal).animate({ opacity: 1 }, 500);
19.
$(
"#notificationsLoader"
).empty();
20.
}
else
{
21.
$(
"#basketItemsWrap li:first"
).before(theResponse);
22.
$(
"#basketItemsWrap li:first"
).hide();
23.
$(
"#basketItemsWrap li:first"
).show(
"slow"
);
24.
$(
"#notificationsLoader"
).empty();
25.
}
26.
27.
}
28.
});
29.
30.
});
The Highlights:
- splitting the ID of the clicked “add-to-basket” image which is “featuredProduct_1” from the “_” character & get the databaseID of the product (1)
- inserting the
loader.gif
image inside the element withid="notificationsLoader"
- posting a data with Ajax to our functions.php fil which handles all the server-side jobs. 2 data are posted:
productID
and the action to be done which isaddToBasket
- There are 2 possibilities when the data is posted, the items may already be inside the basket or it may be a new item. So, we have an if clause:
if( $("#productID_" + productIDVal).length > 0){
which checks if an element with ID: productID1 (1 is a variable) exists in the page- if it exist:
- we change the opacity of that object to 0 (make it invisible)
- load the new
<li>product info</li>
response that comes from the functions.php - remove the original
<li>product info</li>
object whose opacity was 0 - and play with the new
<li>product info</li>
object’s opacity to create a blinking effect - empty the contents inside
id="notificationsLoader"
to stop the loading animation
- if it does not exist:
- we insert the response from the functions.php before the first hidden <li> and hide it
- then use jQuery’s show function to display it with an effect
- empty the contents inside
id="notificationsLoader"
to stop the loading animation
- if it exist:
Function For Removing From Basket:
01.
$(
"#basketItemsWrap li img"
).live(
"click"
,
function
(event) {
02.
03.
var
productIDValSplitter = (
this
.id).split(
"_"
);
04.
var
productIDVal = productIDValSplitter[1];
05.
06.
$(
"#notificationsLoader"
).html(
'<img src="images/loader.gif">'
);
07.
08.
$.ajax({
09.
type:
"POST"
,
10.
url:
"inc/functions.php"
,
11.
data: { productID: productIDVal, action:
"deleteFromBasket"
},
12.
success:
function
(theResponse) {
13.
14.
$(
"#productID_"
+ productIDVal).hide(
"slow"
,
function
() {$(
this
).remove();});
15.
$(
"#notificationsLoader"
).empty();
16.
17.
}
18.
});
19.
20.
});
The Highlights:
- As the objects are inserted to basket via Ajax, the new HTML items inside the basket are normally not loaded to the DOM and we can’t reach them via JavaScript. jQuery offers an event named “live” (starting from jQuery 1.3) which loads the new created items to the DOM. So we used this event.
- All other tasks are similar to adding an item, we splitted the HTML element from the “_” character and got the
productID
to be deleted and sent it to functions.php via Ajax.
The Database
We have used a MySQL database in this example with 2 tables:
Products:
Baskets (for keeping the shopping cart of every different session)
The PHP
There is nothing complicated on the PHP part.
Handle The Variables:
01.
session_start();
02.
$sessionID
=
$_COOKIE
[
'PHPSESSID'
];
03.
04.
if
(
$_POST
[
'action'
] !=
''
||
$_GET
[
'action'
] !=
''
) {
05.
if
(
$_POST
[
'action'
] ==
''
)
06.
{
07.
$action
=
$_GET
[
'action'
];
08.
$productID
=
$_GET
[
'productID'
];
09.
$noJavaScript
= 1;
10.
}
else
{
11.
$action
=
$_POST
[
'action'
];
12.
$productID
=
$_POST
[
'productID'
];
13.
$noJavaScript
= 0;
14.
}
15.
}
The Highlights:
- we create a session variable so every different user will have their own baskets
- understand if the request comes from a POST (Ajax) or GET (JS disabled) request and get the
action
&productID
variables - if it is a GET request we change the value of a variable named
$noJavaScript
to 1
PHP For Add To Basket:
01.
if
(
$action
==
"addToBasket"
){
02.
03.
$productInBasket
= 0;
04.
$productTotalPrice
= 0;
05.
06.
$query
=
"SELECT * FROM products WHERE productID = "
.
$productID
;
07.
$result
= mysql_query(
$query
);
08.
$row
= mysql_fetch_array(
$result
);
09.
10.
$productPrice
=
$row
[
'productPrice'
];
11.
$productName
=
$row
[
'productName'
];
12.
13.
$query
=
"INSERT INTO baskets (productID, productPrice, basketSession) VALUES ('$productID', '$productPrice', '$sessionID')"
;
14.
mysql_query(
$query
)
or
die
(
'Error, insert query failed'
);
15.
16.
$query
=
"SELECT * FROM baskets WHERE productID = "
.
$productID
.
" AND basketSession = '"
.
$sessionID
.
"'"
;
17.
$result
= mysql_query(
$query
)
or
die
(mysql_error());;
18.
19.
while
(
$row
= mysql_fetch_array(
$result
, MYSQL_ASSOC))
20.
{
21.
$totalItems
=
$totalItems
+ 1;
22.
$productTotalPrice
=
$productTotalPrice
+
$row
[
'productPrice'
];
23.
}
24.
25.
if
(
$noJavaScript
== 1) {
26.
header(
"Location: ../index.php"
);
27.
}
else
{
28.
echo
(
'<li id="productID_'
.
$productID
.
'"><a href="inc/functions.php?action=deleteFromBasket&productID='
.
$productID
.
'" onClick="return false;"><img src="images/delete.png" id="deleteProductID_'
.
$productID
.
'"></a> '
.
$productName
.
'('
.
$totalItems
.
' items) - $'
.
$productTotalPrice
.
'</li>'
);
29.
}
30.
31.
}
The Highlights:
- we insert the product to the database. If
$noJavaScript
to 1 we redirect to the index.php else we create a <li> element including the product’s details &echo
it so we can insert it via jQuery.
PHP For Delete From Basket:
01.
if
(
$action
==
"deleteFromBasket"
){
02.
03.
$query
=
"DELETE FROM baskets WHERE productID = "
.
$productID
.
" AND basketSession = '"
.
$sessionID
.
"'"
;
04.
mysql_query(
$query
)
or
die
(
'Error, delete query failed'
);
05.
06.
if
(
$noJavaScript
== 1) {
07.
header(
"Location: ../index.php"
);
08.
}
09.
}
The Highlights:
- we delete the product to the database. If
$noJavaScript
to 1 we redirect to the index.php
PHP For Getting The Basket (For Initial Load)
Like mentioned before, we create a function to get the basket’s current situation, so it can be loaded in the initial loading of the page.
01.
function
getBasket(){
02.
03.
session_start();
04.
$sessionID
=
$_COOKIE
[
'PHPSESSID'
];
05.
06.
$query
=
"SELECT * FROM baskets WHERE basketSession = '"
.
$sessionID
.
"' GROUP BY productID ORDER By basketID DESC"
;
07.
$result
= mysql_query(
$query
);
08.
//echo $query;
09.
10.
while
(
$row
= mysql_fetch_array(
$result
, MYSQL_ASSOC))
11.
{
12.
13.
$query2
=
"SELECT * FROM products WHERE productID = "
.
$row
[
'productID'
];
14.
$result2
= mysql_query(
$query2
);
15.
$row2
= mysql_fetch_array(
$result2
);
16.
17.
$productID
=
$row2
[
'productID'
];
18.
$productPrice
=
$row2
[
'productPrice'
];
19.
$productName
=
$row2
[
'productName'
];
20.
21.
$query2
=
"SELECT COUNT(*) AS totalItems FROM baskets WHERE basketSession = '"
.
$sessionID
.
"' AND productID = "
.
$productID
;
22.
$result2
= mysql_query(
$query2
);
23.
$row2
= mysql_fetch_array(
$result2
);
24.
$totalItems
=
$row2
[
'totalItems'
];
25.
$basketText
=
$basketText
.
'<li id="productID_'
.
$productID
.
'"><a href=inc/functions.php?action=deleteFromBasket&productID='
.
$productID
.
' onClick="return false;"><img src="images/delete.png" id="deleteProductID_'
.
$productID
.
'"></a> '
.
$productName
.
'('
.
$totalItems
.
' items) - $'
. (
$totalItems
*
$productPrice
) .
'</li>'
;
26.
27.
}
28.
echo
$basketText
;
29.
}
The Highlights:
- This is a standard PHP function which creates the HTML for the items in the basket with a loop
And, the Ajaxed basket built with jQuery & PHP is ready-to-use.
P.S. To make the example work on your side, you should be creating a new database with the jBasket.sql file inside the download package & configure the database connection information inside “inc/db.php” file.
Requirements: jQuery 1.3+, PHP & MySQL
Demo: http://webresourcesdepot.com/wp-content/uploads/file…