Ken Phan's Blog

Ken Phan Blog
load ...
Anger
Cry
Glad
Happy
Laugh
Quiet
Sad
Silence
Tongue
Undecided
Wink
Trao yêu thương để nhận thương yêu
"To the world you may be one person, but to one person you may be the world ..."

Buôn chuyện

00 / 00
Ken Phan's Blog [kenphan.info] Ken Phan's Blog [kenphan.info] Ken Phan's Blog [kenphan.info] Ken Phan's Blog [kenphan.info] Ken Phan's Blog [kenphan.info] Ken Phan's Blog [kenphan.info]
Bạn đang ở » Trang chủ » Thủ thuật » Hướng dẫn dùng AJAX (jQuery) & PHP tạo giỏ hàng

Hướng dẫn dùng AJAX (jQuery) & PHP tạo giỏ hàng

Viết lúc 10:45 ngày 13/11/2009 bởi Administrator .

Đã lâu rồi không viết hướng dẫn về jQuery. Hôm nay, buồn buồn không biết làm gì ... viết 1 bài hướng dẫn sử dụng jQuery AJAX (JSON) và PHP để tạo 1 giỏ hàng đơn giản.

Có lẽ, việc tạo ra 1 giỏ hàng không có gì là quá khó khăn với các coder pro ... còn newbie thì sao ?! .... Nếu bạn cảm thấy mình đủ skill để viết được 1 giỏ hàng thì xin bỏ qua dùm bài hướng dẫn này. Không nên đã kích, chém gió bừa bãi làm tổn hại đến nhân phẩm và đạo đức "giả" của em

Đùa giỡn thế đủ oỳ ... chúng ta vào vấn đề thôi. Để hiểu được bài viết này, các bạn cần có 1 chút kiến thức căn bản về jQuery, JSON, và PHP.

http://kenphan.info

Để viết bài hướng dẫn này tớ đã mất 1 đêm để design 1 cái demo ... đóa  ... trước giờ viết hướng dẫn nhìn demo cái nào cái nấy đều ... stupid ... hết. Cho nên lần này quyết tâm design cho thật đẹp. Nhìn cái hình ở trên đê ... cũng cool nhỡ ^^

Okay,. Ở bài này, tớ sẽ không hướng dẫn cách cắt dựng HTML CSS đâu nhé.

Bước 1

Bạn cần download bộ hình ảnh tớ đã cắt sẵn để dễ dàng read & try theo hướng dẫn của tớ (step by step). Click me to download images

Bước 2

Trước hết, chúng ta phải tạo cho mình 1 Cơ sở dữ liệu (CSDL). Ở đây tớ sẽ không tạo CSDL mà sẽ clone 1 cái giống thế. Tạo 1 file gọi là "cloneDB.php" với PHP Code như sau:

<?
$GLOBAL['db'] = array(
	array(
		'cartid'	=> 1,
		'name'		=> 'Product 01',
		'price'		=> 1200,
		'image'		=> '1.jpg'
	),
	array(
		'cartid'	=> 2,
		'name'		=> 'Product 02',
		'price'		=> 1100,
		'image'		=> '2.jpg'
	),
	array(
		'cartid'	=> 3,
		'name'		=> 'Product 03',
		'price'		=> 900,
		'image'		=> '3.jpg'
	),
	array(
		'cartid'	=> 4,
		'name'		=> 'Product 04',
		'price'		=> 1200,
		'image'		=> '4.jpg'
	),
	array(
		'cartid'	=> 5,
		'name'		=> 'Product 05',
		'price'		=> 1400,
		'image'		=> '5.jpg'
	),
	array(
		'cartid'	=> 6,
		'name'		=> 'Product 06',
		'price'		=> 1680,
		'image'		=> '6.jpg'
	),
	array(
		'cartid'	=> 7,
		'name'		=> 'Product 07',
		'price'		=> 2000,
		'image'		=> '7.jpg'
	),
	array(
		'cartid'	=> 8,
		'name'		=> 'Product 08',
		'price'		=> 1400,
		'image'		=> '8.jpg'
	),
	array(
		'cartid'	=> 9,
		'name'		=> 'Product 09',
		'price'		=> 1230,
		'image'		=> '9.jpg'
	),
	array(
		'cartid'	=> 10,
		'name'		=> 'Product 10',
		'price'		=> 1250,
		'image'		=> '10.jpg'
	)
);
?>

Nhìn vào đoạn code PHP Clone trên. Chúng ta thấy rằng, có 1 mãng gồm các mãng con. Trong đó gồm có các key thay cho field trong 1 table gồm: cartid, name, price, image và info.

Bước 3

Đã có CSDL oỳ, tiếp đến sẽ nói về cấu trúc của project chúng ta đang viết. Nó sẽ như thế này:

+ cart
	- css
    - js
    - images
    - index.php
    - functions.php
    - cloneDB.php
    - cart.php

Bạn tạo trước cấu trúc giống như thế rồi hãy đọc tiếp nhé . Lưu ý rằng bạn cần extract hình ảnh từ bước 1 vào thư mục cart/images.

Bước 4

Mở file "index.php" và nhập vào đoạn mã sau:

<!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" />
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://kenphan.info/clientscript/js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.cart.js"></script>
<title>jQuery PHP Add to cart Demo</title>
<!--[if IE]>
<style type="text/css">
#body #products .product .price { margin-top:3px; }
</style>
<![endif]-->
</head>
<body>
<div id="container">
	<div id="header">
		<h1><a href="/">jQuery PHP Add to cart Demo</a></h1>
	</div>
    <div id="body" class="clearfix">
		<div id="products" class="clearfix">
			<div class="product">
                <div class="busy"><div></div></div>
                <div class="name">Product 01</div>
                <div class="images">
					<a href="./cart.php?act=add&id=1" rel="addToCart"><img src="images/1.jpg" /></a>
                </div>
               	<div class="price">$1.200</div>
                <div class="add">
                	<a href="./cart.php?act=add&id=1" rel="addToCart">Add to cart</a>
                </div>
            </div>
            <div class="product">
            	<div class="busy"><div></div></div>
                <div class="name">Product 02</div>
                <div class="images">
                	<a href="./cart.php?act=add&id=2" rel="addToCart"><img src="images/2.jpg" /></a>
                </div>
               	<div class="price">$1.100</div>
                <div class="add">
                	<a href="./cart.php?act=add&id=2" rel="addToCart">Add to cart</a>
                </div>
            </div>
            <div class="product">
                <div class="busy"><div></div></div>
                <div class="name">Product 03</div>
                <div class="images">
                	<a href="./cart.php?act=add&id=3" rel="addToCart"><img src="images/3.jpg" /></a>
                </div>
               	<div class="price">$900</div>
                <div class="add">
                	<a href="./cart.php?act=add&id=3" rel="addToCart">Add to cart</a>
                </div>
            </div>
            <div class="product">
                <div class="busy"><div></div></div>
                <div class="name">Product 04</div>
                <div class="images">
                	<a href="./cart.php?act=add&id=4" rel="addToCart"><img src="images/4.jpg" /></a>
                </div>
               	<div class="price">$1.200</div>
                <div class="add">
                	<a href="./cart.php?act=add&id=4" rel="addToCart">Add to cart</a>
                </div>
            </div>
				<div class="product last">
                <div class="busy"><div></div></div>
                <div class="name">Product 05</div>
                <div class="images">
                	<a href="./cart.php?act=add&id=5" rel="addToCart"><img src="images/5.jpg" /></a>
                </div>
               	<div class="price">$1.400</div>
                <div class="add">

                	<a href="./cart.php?act=add&id=5" rel="addToCart">Add to cart</a>
                </div>
            </div>
            <div class="product">
                <div class="busy"><div></div></div>
                <div class="name">Product 06</div>
                <div class="images">
                	<a href="./cart.php?act=add&id=6" rel="addToCart"><img src="images/6.jpg" /></a>

                </div>
               	<div class="price">$1.680</div>
                <div class="add">
                	<a href="./cart.php?act=add&id=6" rel="addToCart">Add to cart</a>
                </div>
            </div>
            <div class="product">
                <div class="busy"><div></div></div>
                <div class="name">Product 07</div>
                <div class="images">
                	<a href="./cart.php?act=add&id=7" rel="addToCart"><img src="images/7.jpg" /></a>
                </div>
               	<div class="price">$2.000</div>
                <div class="add">
                	<a href="./cart.php?act=add&id=7" rel="addToCart">Add to cart</a>

                </div>
            </div>
            <div class="product">
                <div class="busy"><div></div></div>
                <div class="name">Product 08</div>
                <div class="images">
                	<a href="./cart.php?act=add&id=8" rel="addToCart"><img src="images/8.jpg" /></a>
                </div>

               	<div class="price">$1.400</div>
                <div class="add">
                	<a href="./cart.php?act=add&id=8" rel="addToCart">Add to cart</a>
                </div>
            </div>
            <div class="product">
                <div class="busy"><div></div></div>
                <div class="name">Product 09</div>
                <div class="images">
                	<a href="./cart.php?act=add&id=9" rel="addToCart"><img src="images/9.jpg" /></a>
                </div>
               	<div class="price">$1.230</div>
                <div class="add">
                	<a href="./cart.php?act=add&id=9" rel="addToCart">Add to cart</a>
                </div>
            </div>
            <div class="product last">
                <div class="busy"><div></div></div>
                <div class="name">Product 10</div>
                <div class="images">
                	<a href="./cart.php?act=add&id=10" rel="addToCart"><img src="images/10.jpg" /></a>
                </div>
               	<div class="price">$1.250</div>
                <div class="add">

                	<a href="./cart.php?act=add&id=10" rel="addToCart">Add to cart</a>
                </div>
            </div>
        </div>
		<div id="cart">
        	<div class="busy"><div></div></div>
	   		<h1>Your Cart</h1>
            <div class="info">
            	<p><strong id="totalItems">3</strong> items in cart</p>
                <p>Total price of items: <strong id="totalPrice">$4.200</strong> USD</p>
            </div>
            <div class="button">
            	<p><a href="#">›› Checkout cart</a></p>
                <p><a href="./cart.php?act=removeall" rel="removeAllCart">›› Remove all items</a></p>
            </div>
		</div>
	</div>
   </div>
   <div id="footer">
        <p>Power by <a href="http://kenphan.info">Ken Phan</a> © 2009. All rights reserved. Thanks <a href="http://jquery.com" target="_blank">jQuery</a>
    </div>
</div>
</body>
</html>

Vì bài viết này, không nhằm mục đích hướng dẫn CSS nên việc cắt dựng sẽ bỏ qua 1 bên. Trong file "index.php" chúng ta thấy rằng tài liệu đã embed vào 1 file styles.css và 2 file js là jquery.cart.js /  jQuery.min.js. Tạm thời thì jquery.min.js sẽ lấy từ blog của tớ còn jquery.cart.js sẽ được đề cập đến sau.

Mở file CSS "styles.css" và nhập vào đoạn mã sau:

/* Every time */
/* ----------  Reset */
html, body, div, h1, h2, h3, h4, h5, h6, ul, ol, dl, li, dt, dd, p, blockquote, pre, form, fieldset, table, th, td { margin:0; padding:0;}
/* ------------------------------ */

body {
	margin:0;
	background:#f1f1f1;;
	color:#666;
	font-size: 12px; /* Resets 1em to 10px */
	font-family: Helvetica, Tahoma,Arial,sans-serif;
	behavior:url("/webshop/script/default/css/csshover.htc");
}

.busy {
	position:absolute;
	left:50%;
	top:50%;
	margin-left:-15px;
	width:30px;
	height:30px;
	background:url(../images/busyBg.png) no-repeat center center;
	display:none;
}
.busy div {
	width:30px;
	height:30px;
	background:url(../images/busy.gif) no-repeat center center;
}

a:link,
a:visited,
a:active {
	text-decoration:none;
	color:#555;
}
a:hover {
	color:#000;
}
#container {
	margin:0 auto;
	width: 980px;
}
#header {
	padding:10px 0;
	margin-bottom:5px;
}
#header h1 a {
	display: block;
	padding: 20px 5px 20px 20px;
	text-decoration:none;
}

#body {
}
#body #cart {
	float:right;
	width:195px;
	background:#e1e1e1;
	padding:10px;
	position:relative;
}
#body #cart .info {
	padding:3px;
	border-bottom:1px solid #fff;
	margin-bottom:5px;
}
#body #cart .info p,
#body #cart .button p {
	margin-bottom:3px;
}
#body #cart .button {
	padding:3px;
}
#body #products {
	float:left;
	width:750px;
	padding:10px 0px 10px 10px;
	background:#e1e1e1;
}
#body #products .product {
	float:left;
	width:130px;
	margin-right:10px;
	margin-bottom:10px;
	padding:5px;
	position:relative;
	background: url(../images/productBg.png) no-repeat;
}
#body #products .product:hover {
	background-image:url(../images/productBgHover.png);
}
#body #products .product:hover .images img {
	border-color:#e1e1e1;
}
#body #products .product:hover .add {
	background:#fff;
	border-color:#e1e1e1
}
#body #products .last {
	margin-right:0px;
}
#body #products .product .name {
	text-align:center;
	font-weight:bold;
	padding:5px;
}
#body #products .product .images {
	cursorointer;
	text-align:center;
}
#body #products .product .images img {
	border:1px solid #fff;
}
#body #products .product .price {
	text-align:center;
	margin-top:5px;
	font-size:14px;
	padding:3px;
	color:#060;
}
#body #products .product .add {
	border:1px solid #fff;
	text-align:center;
	padding:2px;
}

#footer {
	margin-top:5px;
	padding-top:10px;
}
#footer p {
	color:#666;
	font-size:11px;
	margin-top:10px
}
/* CLEARFIX */
* html .clearfix {
	height: 1%; /* IE5-6 */
}

.clearfix {
	display: inline-block; /* IE7xhtml*/
}

html[xmlns] .clearfix {
	display: block; /* O */
}

.clearfix:after {
	clear: both;
	content: "."; /* FF, O, etc. */
	display: block;
	height: 0;
	line-height: 0;
	visibility: hidden;
}

Lúc này, bạn có thể chạy thử website rồi đó. Nó đã có hình dạng rồi nhỉ .

Bước 5

Tiếp theo, chúng ta cần include "cloneDB.php" vào "index.php" để lấy dữ liệu từ clone array mà chúng ta đã tạo trước đó. Mở file "index.php" và thêm đoạn mã sau vào dòng đầu tiên:

<?php
include ('cloneDB.php');
?>

Tiếp tục, bạn để ý cấu trúc thẻ HTML của "index.php". Có thể thấy rằng, bao phủ các product item là <div id="products" class="clearfix">. Xóa từ thẻ <div id="products" class="clearfix"> đến thẻ đóng </div> của nó. Và cho đoạn mã này vào giữa nó:

<div id="products" class="clearfix">
	<?php foreach($GLOBAL['db'] as $i => $row):?>
    <?php if(($i+1)%5) {?>
    <div class="product">
    <?php } else {?>
    <div class="product last">
    <?php }?>
    <div class="busy"><div></div></div>
    <div class="name"><?php echo $row['name'] ?></div>
    <div class="images">
    <a href="./cart.php?act=add&id=<?php echo $row['cartid'] ?>" rel="addToCart"><img src="images/<?php echo $row['image']?>" /></a>
    </div>
    <div class="price"><?php echo $fn->transfer_money($row['price']); ?></div>
    <div class="add">
    <a href="./cart.php?act=add&id=<?php echo $row['cartid'] ?>" rel="addToCart">Add to cart</a>
    </div>
    </div>
    <?php endforeach; ?>
</div>

"index.php" của ta sẽ như sau:

<?php
include ('cloneDB.php');
?>
<!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" />
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://kenphan.info/clientscript/js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.cart.js"></script>
<title>jQuery PHP Add to cart Demo</title>
<!--[if IE]>
<style type="text/css">
#body #products .product .price { margin-top:3px; }
</style>
<![endif]-->
</head>
<body>
<div id="container">
	<div id="header">
		<h1><a href="/">jQuery PHP Add to cart Demo</a></h1>
	</div>
    <div id="body" class="clearfix">
        <div id="products" class="clearfix">
            <?php foreach($GLOBAL['db'] as $i => $row):?>
            <?php if(($i+1)%5) {?>
            <div class="product">
            <?php } else {?>
            <div class="product last">
            <?php }?>
            <div class="busy"><div></div></div>
            <div class="name"><?php echo $row['name'] ?></div>
            <div class="images">
            <a href="./cart.php?act=add&id=<?php echo $row['cartid'] ?>" rel="addToCart"><img src="images/<?php echo $row['image']?>" /></a>
            </div>
            <div class="price"><?php echo $row['price']; ?></div>
            <div class="add">
            <a href="./cart.php?act=add&id=<?php echo $row['cartid'] ?>" rel="addToCart">Add to cart</a>
            </div>
            </div>
            <?php endforeach; ?>
        </div>
		<div id="cart">
        	<div class="busy"><div></div></div>
	   		<h1>Your Cart</h1>
            <div class="info">
                <p><strong id="totalItems">1</strong> items in cart</p>
                <p>Total price of items: <strong id="totalPrice">$123</strong> USD</p>
            </div>
            <div class="button">
            	<p><a href="#">›› Checkout cart</a></p>
                <p><a href="./cart.php?act=removeall" rel="removeAllCart">›› Remove all items</a></p>
            </div>
    	</div>
   </div>
   <div id="footer">
        <p>Power by <a href="http://kenphan.info">Ken Phan</a> © 2009. All rights reserved. Thanks <a href="http://jquery.com" target="_blank">jQuery</a>
    </div>
</div>
</body>
</html>

Lúc này, bạn có thể chạy thử nó rồi đóa ... xem thử nó thế nào nhé ^^

Bước 6

Sau khi hoàn thành bước 5, có 1 điều mà chắc hẵn bạn sẽ thấy ... price nhìn có vẽ không mượt mà lém ... Okay, mở file "functions.php" và cho vào dòng mã sau:

<?php

class Functions
{
	function transfer_money ($number)
	{
		$money = number_format($number);
		$money = preg_replace('/,/i', '.', $money);
		return '$' . $money;
	}
}
?>

Ở đây, tớ viết 1 class có tên là Functions và trong đóa có function transfer_money(). Function này sẽ đổi 1 số sang tiền... ví dụ có thể là thế này: 1000 => $1.000. 

Mở lại file "index.php" và thêm đoạn mã sau:

<?php
include ('functions.php');
$fn = new Functions();
?>

vào phía dưới:

<?php
include ('cloneDB.php');
?>

Nó sẽ thế này:

<?php
include ('cloneDB.php');
include ('functions.php');
$fn = new Functions();
?>

Kiếm đoạn mã:

<div class="price"><?php echo $row['price']; ?></div>

và thay thành:

<div class="price"><?php echo $fn->transfer_money($row['price']); ?></div>

thử try xem nào ... lúc này số tiền có vẽ hợp lý hơn rồi nhỉ

Bước 7

Tiếp đến, tạo 1 file có tên là "jquery.cart.js" cho vào thư mục js và nhập vào đoạn mã sau:

$(document).ready(function(){
	// for add item to cart
	$('[rel=addToCart]').click(function(){
		var _seft = $(this);
		var url = _seft.attr('href');
		$.ajax({
			url: url,
			type: 'get',
			dataType: 'json',
			beforeSend: function (){
				_seft.parent().parent().find('.busy').show();
			},
			success: function(db) {
				_seft.parent().parent().find('.busy').hide();
				$('#totalItems').html(db.total);
				$('#totalPrice').html(db.price);
			}
		});
		return false;
	});
	// for remove all cart
	$('[rel=removeAllCart]').click(function(){
		var _seft = $(this);
		var url = _seft.attr('href');
		$.ajax({
			url: url,
			type: 'get',
			dataType: 'html',
			beforeSend: function (){
				_seft.parent().parent().parent().find('.busy').show();
			},
			success: function(db) {
				_seft.parent().parent().parent().find('.busy').hide();
				$('#totalItems').html('0');
				$('#totalPrice').html('$0');
			}
		});
		return false;
	});
	
});

Giải thích

Dòng 3: $('[rel=addToCart]').click(function(){ ... } tạo sự kiện onclick cho thẻ a có rel="addTo Cart". Sự kiện được gọi khi có người chọn giỏ hàng.
Dòng 4: var _seft = $(this); Tạo biến _seft lưu lại object hiện thời của event.
Dòng 5: var url = _seft.attr('href'); Tạo biến URL lưu đường dẫn của thẻ A
Dòng 6: đến 18 là gọi AJAX.
Dòng 10: beforeSend: function (){ ...} có nghĩa là function sẽ được chạy trước khi AJAX request.
Dòng 11: _seft.parent().parent().find('.busy').show();  hiện thẻ <div class="busy"><div></div></div>
Dòng 14: _seft.parent().parent().find('.busy').hide(); ẩn thẻ <div class="busy"><div></div></div>
Dòng 15: $('#totalItems').html(db.total); lấy giá trị trả db.total cho vào <strong id="totalItems">...</strong>
Dòng 16: $('#totalPrice').html(db.price); lấy giá trị trả db.price cho vào <strong id="totalPrice">...</strong>

Các dòng còn lại tương tự như trên.

Bước 8

Sau khi thực hiện xong Bước 7, chắc bạn cũng đã try thử oỳ ... ... không được gì phải không ?! vì chúng ta còn thiếu chưa xử lý giỏ hàng mà.

Ở bước này, chúng ta sẽ bắt tay xây dựng 1 class dùng làm giỏ hàng. Mở "functions.php" và replace tất cả bằng đoạn mã sau:

<?php

class Functions
{
	function transfer_money ($number)
	{
		$money = number_format($number);
		$money = preg_replace('/,/i', '.', $money);
		return '$' . $money;
	}
}

class Cart 
{
	var $name = "myCart";
	
	function __construct()
	{
		session_start();
	}
	
	function add($id)
	{
		$cart = $_SESSION[$this->name];
	
		if(!isset($cart))
			$cart = array();
		
		if(isset($cart[$id]))
			$cart[$id] += 1;
		else $cart[$id] = 1;
		
		$_SESSION[$this->name] = $cart;
	}
	
	function removeall()
	{
		unset($_SESSION[$this->name]);
	}
	
	function pcount()
	{
		$cart = $_SESSION[$this->name];
		
		if(!isset($cart))
			return '0';
		
		$count = 0;
		foreach($cart AS $k => $v) {
			$count += $v;
		}
		return $count;
		
	}
	
	function price($db)
	{
		$cart = $_SESSION[$this->name];
		
		if(!isset($cart))
			return '0';
		
		$total = 0;
		foreach ($cart as $id => $qty) 
		{
			foreach($db as $k => $v)
			{
				if($v['cartid'] == $id) {
					$total += $v['price'] * $qty;
				}
			}
		}
		return $total;
	}
}
?>

Để ý thì thấy rằng, tớ tạo thêm 1 class nữa đó là "Cart". Trong đó có các function là: add, removeall, pcount và price. Ý nghĩa của nó như sau:

add: dùng để thêm sản phẩm vào giỏ hàng.
removeall xóa giỏ hàng.
pcount tính tổng các sản phẩm có trong giỏ hàng.
price tính tổng số tiền trong giỏ hàng.

Giải thích function add

function add($id)
{
	$cart = $_SESSION[$this->name];

	if(!isset($cart))
		$cart = array();
	
	if(isset($cart[$id]))
		$cart[$id] += 1;
	else $cart[$id] = 1;
	
	$_SESSION[$this->name] = $cart;
}

Đầu tiên, tạo 1 biến có tên là $cart và cho nó bằng $_SESSION[$this->name]. $this->name là tên của SESSION giỏ hàng (ở đây là myCart).

Tiếp theo, kiểm tra nếu $cart chưa có giá trị thì chuyển nó thành dạng mãng. Nếu $cart[$id] đã có giá trị thì $cart[$id] đó sẽ cộng thêm 1 sản phẩm, ngược lại là 1.

Lưu ý rằng ở đây, giá trị của SESSION là tổng số sản phẩm đó có trong giỏ hàng và key của nó là id của sản phẩm.

Giải thích function removeall

function removeall()
{
	unset($_SESSION[$this->name]);
}

Xóa đi $_SESSION[$this->name].

Giải thích function pcount

function pcount()
{
	$cart = $_SESSION[$this->name];
	
	if(!isset($cart))
		return '0';
	
	$count = 0;
	foreach($cart AS $k => $v) {
		$count += $v;
	}
	return $count;
	
}

Dòng 5: nếu $cart chưa có giá trị thì function sẽ trả về 0.
Dòng 8: cho biến $count bằng 0
Dòng 9: foreach $cart và cộng giá trị của tất cả các sản phẩm có trong giỏ hàng.

Giải thích function price

function price($db)
{
	$cart = $_SESSION[$this->name];
	
	if(!isset($cart))
		return '0';
	
	$total = 0;
	foreach ($cart as $id => $qty) 
	{
		foreach($db as $k => $v)
		{
			if($v['cartid'] == $id) {
				$total += $v['price'] * $qty;
			}
		}
	}
	return $total;
}

Dòng 11: foreach $db, dòng tiếp theo sẽ kiểm tra nếu id có trong SESSION mà bằng với cartid thì sẽ nhân số tiền của sản phẩm đó với tổng số sản phẩm đó có trong giỏ hàng và cho vào biến $total.

Bước 9

Mở "index.php" và thêm vào như sau:

$cart	= new Cart();

Tìm đoạn

<p><strong id="totalItems">1</strong> items in cart</p>
<p>Total price of items: <strong id="totalPrice">$123</strong> USD</p>

và thay thành:

<p><strong id="totalItems"><?php echo $cart->pcount()?></strong> items in cart</p>
<p>Total price of items: <strong id="totalPrice"><?php echo $fn->transfer_money( $cart->price($GLOBAL['db']) ) ?></strong> USD</p>

Bước 10

Mở "cart.php" và thêm đoạn mã sau đây:

<?php

//error_reporting (E_ALL);

include ('cloneDB.php');
include ('functions.php');

$fn		= new Functions();
$cart	= new Cart();

$action = $_GET['act'];
// Define Ajax Request
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

switch ($action) {
	case 'add':
		$cart->add($_GET['id']);
		if(!IS_AJAX)
			header('Location: ' . $_SERVER['HTTP_REFERER']);
		else
			echo "({ total: {$cart->pcount()}, price: '{$fn->transfer_money( $cart->price($GLOBAL['db']) )}' })";
		break;
	case 'removeall':
		$cart->removeall();
		break;
}
				 
?>

Giải thích:

define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

Dòng này sẽ xác định 1 hằng số là IS_AJAX. Nếu nó trả về TRUE có nghĩa là hiện request là AJAX và ngược lại thì bình thường. Đoạn mã trên rất hữu dụng.

$action = $_GET['act'];
switch ($action) { ... }

Dùng switch $action ... để truy xuất dữ liệu từ GET act=xxx. Khi đường dẫn có dạng cart.php?act=add&id=xx thì sẽ gọi đoạn:

$cart->add($_GET['id']);
if(!IS_AJAX)
	header('Location: ' . $_SERVER['HTTP_REFERER']);
else
	echo "({ total: {$cart->pcount()}, price: '{$fn->transfer_money( $cart->price($GLOBAL['db']) )}' })";

Đoạn mã trên sẽ gọi method add() của class Cart và kiểm tra nếu request là AJAX thì sẽ trả về dữ liệu định dạng JSON. Ngược lại thì redirect lại trang vừa gọi.

$cart->removeall();

Nếu $action là removeall thì đoạn mã trên sẽ gọi method removeall() của class Cart xóa đi SESSION myCart.

Đến đây mệt mõi oỳ ... mọi người từ từ ngâm cứu tiếp nhé ... tớ ngủ đây g9

Cảm nhận của mọi người

  • Thật là phức tạp quá đi mà .. bỏ nghề code thôi bác Ken
    Posted at 2 years . Reply
    + 15 points . Good . Bad
  • Administrator
    ... bác Phi gác kiếm rồi àh ?! .. chắc làm PM rùi nên không code nữa ...
    Posted at 2 years . Reply
    + 15 points . Good . Bad
  • oh bạn viết hay quá.ái mộ bạn wa.
    mày đi chết đi mày.
    Posted at 2 years . Reply
    + 15 points . Good . Bad
  • Mr Long
    Bac Ken post vai bai chi cach cat css hen. Thanks
    Posted at 2 years . Reply
    + 15 points . Good . Bad
  • minh
    ban co the quay film cac buoc thao tac dc ko?doc cai nay hieu chet lien lun.chang biet cau truc du lieu ra sao ?nhin cu roi len a!
    Posted at 2 years . Reply
    + 15 points . Good . Bad
  • Administrator
    bạn download về xem trước đi. Nếu vẫn chưa hiểu mình ghi video lun
    Posted at 2 years . Reply
    + 15 points . Good . Bad
  • Minh Diep
    Thanks bạn, bài viết khá hay và chi tiếtP/s: Bạn Ken có phải đang học ở Việt Chuyên không nhỉ (highwind)
    Posted at 2 years . Reply
    + 15 points . Good . Bad
  • Administrator
    @Mr Long: sẽ rất sớm thôi. làm biếng design template quá.@Minh Diep: Chắc bạn nhầm oỳ mình hok có học ở Việt Chuyên
    Posted at 2 years . Reply
    + 15 points . Good . Bad
  • Cái lão này, lúc trước nhờ làm cái cart vầy chả chịu làm giùm >"
    Posted at 2 years . Reply
    + 15 points . Good . Bad
  • Nguyen Duy Phuong
    Phuc Tap That.Nhung Cung Kham Phuc,Ban Viet Chi Rat Tot.Chac CUng La Dang Pro code web ha?Minh Dang Lam Do an Web,co phan GioHang Nhung Viet Bang PHP Thoi.Tim Nhieu bai rui nhung chua thay co bai nao doc hieu het.ban giup minh dc ko??
    Posted at 2 years . Reply
    + 15 points . Good . Bad
  • Administrator
    ... để hiểu được bài viết này, bạn cần tìm hiểu về căn bản jquery đi đã. Bỏ khoảng 2,3 ngày để tìm hiểu về nó là bạn có thể viết được "tất tần tật" những gì bạn muốn rồi.thân !
    Posted at 2 years . Reply
    + 15 points . Good . Bad
  • duachuot
    Ham mo pac' Ken wa', bac' cho e xin cai YM co j e hoi dc ko? YM cua e la nakata_1268.
    Posted at 2 years . Reply
    + 15 points . Good . Bad
  • Administrator
    hehe Welcome duachuot, cảm ơn duachuot nhé
    Bạn để ý trên cùng bên tay trái ... gần avatar có cái hình smileys và online/offline đó ! Nick mình ở đó
    Posted at 2 years . Reply
    + 15 points . Good . Bad
  • Bai viet rat hay ...........
    Ban co the lam mot vi du ve ajax viet bang java gui request toi server nhu sau
    lay thong tin tren thanh address "http://localhost/test/#Home"
    cat lay chu Home gui request voi bien $_POST['url'] = 'Home';
    va minh tuy bien thong qua bien post nay de dung PHP dieu khien "
    cam on ban truoc nha
    ban co the gui cho toi qua gmail:anhchangthode22145@gmail.com
    Posted at 2 years . Reply
    + 15 points . Good . Bad
  • giỏi quá đi bạn ơi! đang ở đâu vậy rủ đi nhậu nha!
    Posted at 2 years . Reply
    + 15 points . Good . Bad
  • banglangtim
    Thank bạn nhé. bạn có thê viết bài về dùng jquery trong joomla được k?
    2 Replies. Posted at 2 years . Reply
    + 15 points . Good . Bad
    • Administrator
      àh, mình chưa biết nhiều về Joomla. Nếu bạn có thắc mắc gì về PHP hoặc jQuery thì mình sẽ cố gắng nếu có thể
      1 Replies. Posted at 2 years . Reply
      + 15 points . Good . Bad
      • Joomla chi cho mệt, phức tạp .. tự code thích hơn
        Posted at 2 years
        + 15 points . Good . Bad
  • ung ho thang ban cai ne
    Posted at 2 years . Reply
    + 15 points . Good . Bad
  • ruvi
    thank bạn nhiều lắm nha, viết rất dễ hiểu và chi tiết. đúng cái mình đang tìm luôn
    1 Replies. Posted at 1 year . Reply
    + 15 points . Good . Bad
    • Administrator
      hok có gì
      Posted at 1 year . Reply
      + 15 points . Good . Bad
  • huy
    tuyệt quá ! đúng thứ đang cần , mình đang tìm hiểu về jquery nhưng cứ y như bị tung hỏa mù
    Posted at 11 months . Reply
    + 15 points . Good . Bad
  • Hoang
    Mình đã làm theo tất cả các bước. Nhưng thấy cái busy nó cứ xoay mãi không xong. Không biết sai chỗ nào. admin giúp mình với
    1 Replies. Posted at 8 months . Reply
    + 15 points . Good . Bad
    • Administrator
      bạn có thể nói rõ hơn ?
      Posted at 8 months . Reply
      + 15 points . Good . Bad
  • Chúc bạn thành công trong công việc!
    Posted at 1 week . Reply
    + 15 points . Good . Bad