สอนทำระบบตะกร้าสินค้าแบบ Drag & Drop (คลิกลาก/วาง) ด้วย jQuery UI
ผมได้ลองใช้ Component ของ jQuery UI คือ Draggable กับ Droppable มาประยุกต์ใช้กับ Add To Cart (หยิบสินค้าใส่ตะกร้า) ซึ่งผมคิดว่ามันก็แจ่มไม่เลวเหมือนกันครับ เพียงแต่ไม่ค่อยมีใครนิยมเอามาใช้กับระบบตะกร้าสินค้าซักเท่าไหร่ครับ ผมก็แค่อยากทำเล่นๆน่ะครับ เผื่อจะมีประโยชน์แก่ผู้ที่สนใจ อยากทำระบบตะกร้าสินค้าแบบ Drag & Drop ครับ และวิธีทำก็ไม่ยากเลยครับ เพราะผมใช้ jQuery UI เข้ามาช่วย ทำให้ไม่ต้องเขียนโค๊ด Drag & Drop เองให้ยุ่งยาก เพียงแต่ต้องรู้วิธีใช้เท่านั้นเองครับ
และผมได้เขียนบทความ สอนทำระบบตะกร้าสินค้า มาแล้ว หลายบทความเหมือนกันครับ ศึกษาได้จาก สอนทำระบบตะกร้าสินค้า
มาดูโค๊ดกันเลยครับ ให้สร้างไฟล์ขึ้นมา 2 ไฟล์ คือ showproduct.php,showcart.php
สำหรับเทเบิล product ให้สร้างตามนี้นะครับ
CREATE TABLE `product` ( `id_pd` int(10) NOT NULL auto_increment, `id_cg` int(5) NOT NULL, `name_pd` varchar(250) default NULL, `detail_pd` text, `amount_pd` int(4) default '0', `price_pd` float(9,2) default '0.00', `img_pd` varchar(20) default NULL, `date_pd` date default NULL, `count_pd` int(7) default '0', PRIMARY KEY (`id_pd`) );1.ไฟล์ showproduct.php -> แสดงรายการสินค้าและสามารถหยิบสินค้าใส่ตะกร้า โดยการลากสินค้ามาวางในตะกร้าสินค้าได้ เราจะเขียนโค๊ด Javascript (jQuery ,AJAX) ในไฟล์นี้ทั้งหมดครับ ให้ใช้โค๊ดดังนี้
<?php
$conn=mysql_connect('localhost','root','root');
mysql_select_db('db_jpcom',$conn);
mysql_query('SET NAMES UTF8');
$rs_pdshow=mysql_query('SELECT * FROM product LIMIT 10') or die(mysql_error());
?>
<!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" />
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.18.custom.min.js"></script>
<title>สอนทำตะกร้าสินค้าแบบ Drag and Drop (ลาก/วาง) ด้วย jQuery UI</title>
<style>
.product {
width: 150px;
padding: 0.5em;
float: left;
margin: 10px 10px 10px 0;
cursor:move;
border:1px dashed #999;
background:#E0E0E0;
font-size:13px;
}
#cart {
font-size:13px;
width: 300px;
padding: 0.5em;
float: left;
margin: 10px;
border:1px dashed #999;
background:#fff;
}
</style>
<script type="text/javascript">
var mycart=$("#cart");
var url='showcart.php?rd='+Math.random()*20;
function dragdrop_pd(){
var playshow;//เก็บเวลาในการแสดงผลตะกร้าสินค้า
if(!mycart.attr('id')){$('body').append('<div id="cart" style="display:none;"></div>');mycart=$("#cart");}
//checkว่ามีการสร้างElementของตะกร้าสินค้าหรือยัง
$( ".product" ).hover(function(ev){//เหตุการณ์เมื่อเมาส์ไปวางที่สินค้าใดๆ
clearInterval(playshow);//เคลียร์เวลาแสดงผลตะกร้าสินค้าก่อนนะ
action2cart(url,mycart);//เรียกใช้Func นี้เพื่อเรียกข้อมูลของตะกร้าสินค้ามาจากอีกไฟล์นึงแบบ AJAX
mycart.css({position:'absolute',top:$(this).position().top+$(this).height(),left:$(this).position().left-10});
//กำหนดตำแหน่งแสดงผล ผมกำหนดให้แสดงใต้สินค้าใดๆที่เอาเมาส์ไปวาง
mycart.show();//แสดงตะกร้าสินค้าโลด
$(this).draggable({//เรียกเมธอด Draggable (คลิกลากสินค้า) ให้ทำงาน
appendTo: "body",//ให้แสดงผลในส่วนของbody
helper: "clone"});//clone ตัวเองด้วยน๊ะจ๊ะ
},function(){//เอาเมาส์ออกจากสินค้าใดๆ
playshow = setInterval(function(){ mycart.fadeOut('slow');},3000);
//กดหนดให้ตะกร้าสินค้าแสดงอีก 3 วิ (3000) แล้วค่อยๆเลือนหายไป (fadeOut)
});
mycart.hover(function(){//เหตุการณ์เมื่อเอาเมาส์วางที่ตะกร้าสินค้า
clearInterval(playshow);//เคลียร์เวลาแสดงผลตะกร้าสินค้า
},function(){//เอาเมาส์ออกจากตะกร้าสินค้า
playshow = setInterval(function(){ mycart.fadeOut('slow');},3000);
//กดหนดให้ตะกร้าสินค้าแสดงอีก 3 วิ (3000) แล้วค่อยๆเลือนหายไป (fadeOut)
});
mycart.droppable({//เรียกเมธอด droppable (วางสินค้าลงตะกร้าสินค้า) ให้ทำงาน
drop: function( event, ui ) {
action2cart(url+"&cartId="+ui.draggable.attr('id'),$(this));
// Add to Cart โลด
}
});
$('.pd_amount').live('keyup',function(){//เหตุการ์เมื่อมีการแก้ไขจำนวนสินค้าที่ตะกร้าสินค้า
setTimeout(function(){action2cart($('#feditcart').attr('action'),mycart,$('#feditcart').serialize(),"POST");},2000);
//หน่วงเวลาก่อนซัก 2 วิ แล้วค่อยส่่งค่าไปอัพเดทจำนวน
});
}
function action2cart(URL,Area,Data,Type){
//มีหน้าที่ส่งค่าแบบ AJAX ให้ทำงานดังนี้ Add 2 Cart,ลบสินค้าในตะกร้า,แก้ไขจำนวนสินค้า
$.ajax({
url:URL,//URL ที่จะส่งข้อมูลไปประมวลผล
type:Type==''?'GET':Type,//ค่าเริ่มต้นเป็น GET
data:Data==''?'':Data,//ค่าเริ่มต้นเป็นค่าว่าง
dataType: 'html',
success: function(data) {//ทำงานเสร็จสมบูรณ์ และคืนค่ากลับมา (data)
Area.html(data);//เอาค่ามาแสดงที่ตะกร้าสินค้า
}
});
}
function delCart(Ele){//Func ลบสินค้าในตะกร้าสินค้า
action2cart(url+"&delCart="+$(Ele).attr('id'),mycart);
//ส่่งค่าเข้าไปในFunc action2cart
}
$(document).ready(function(){//เมื่อเพจนี้ถูกโหลดเรียบร้อยแล้ว
dragdrop_pd();//Func dragdrop_pd() ทำงานโลด
});
</script>
</head>
<body>
<?php while($pdshow=mysql_fetch_assoc($rs_pdshow)){?>
<div class="product" id="<?=$pdshow['id_pd']?>">
<p>
<?=$pdshow['name_pd']?>
</p>
<p><img src="../../img_product/thumb/<?=$pdshow['img_pd']?>" /></p>
</div>
<?php }?>
</div>
</body>
</html>
ในไฟล์นี้จะมีการเรียกใช้ไฟล์ jQuery UI ให้ท่านศึกษา ดาวน์โหลดและติดตั้ง jQuery UI2. ไฟล์ showcart.php -> แสดงรายการสินค้าในตะกร้าสินค้าครับ เป็นไฟล์ที่ใช้ประมวลผลข้อมูลในตะกร้าสินค้า คือ หยิบสินค้าลงในตะกร้า,ลบรายการสินค้าในตะกร้า,แก้ไขจำนวนสินค้าในตะกร้า แล้วนำผลลัพธุ์ไปแสดงในDialogตะกร้าสินค้าของไฟล์ showproduct.php นั่นเองครับ ให้พิมพ์โค๊ดดังนี้
<?php
session_start();
$conn=mysql_connect('localhost','root','root');
mysql_select_db('db_jpcom',$conn);
mysql_query('SET NAMES UTF8');
if(isset($_GET["cartId"])){#Add to cart
$cid=$_GET["cartId"];
$_SESSION["cartcount"]++;
$cartcount=$_SESSION["cartcount"];
$CItemCount="cart$cartcount";
$CartStatus=true;#เอาไว้เก็บสถานะสินค้าว่าลูกค้าเลือกซ้ำหรือไม่
$rs_showpd=mysql_fetch_array(mysql_query("SELECT price_pd FROM product WHERE id_pd=".$cid));
if(count($_SESSION["cartNumber"])!=0 ){
foreach($_SESSION["cartNumber"] as $RecCart){
if($_SESSION[$RecCart][0]==$cid){#หากสินค้าซ้ำกับของเดิม(โดยตรวจสอบจาก ID ของสินค้า)
$_SESSION[$RecCart][1]++;#เพิ่มจำนวนสินค้า
$CartStatus=false;#เปลี่ยนสถานะ
}
}
}
if($CartStatus){#สถานะเป็นtrue แสดงว่าสินค้าไม่ซ้ำกับของเดิม
$_SESSION[$CItemCount][0]=$cid;
$_SESSION[$CItemCount][1]=1;
$_SESSION[$CItemCount][2]=$rs_showpd["price_pd"];
$_SESSION["cartNumber"][$cartcount]=$CItemCount;#ตำแหน่งของแต่ละเรคคอร์ดของสินค้า
}
}
##################################################################
if(isset($_GET["delCart"])){#ต้องการจะลบสินค้า
$RecDel=$_GET["delCart"];
foreach($_SESSION["cartNumber"] as $RecCart){#วนไปจนกว่าจะเจอแถวของสินค้าที่เลือกลบ
if($RecCart==$RecDel){
$CNum =preg_replace("/[^0-9]/", '', $RecCart); // คัดเอาเฉพาะตัวเลข เช่น cart1 จะได้ ค่า 1 เป็นต้น
unset($_SESSION['cartNumber'][$CNum]); // unset แถวที่เก็บสินค้าที่ต้องการลบ
}
unset($_SESSION[$RecDel]);#unset ข้อมูลสินค้าที่เก็บไว้ทั้งหมด
}
}
##################################################################
if(isset($_POST["pd_amount"])){#ต้องการแก้ไขจำนวนสินค้า
$pdid=$_POST["pd_id"];#รหัสของสินค้าทั้งหมด(จัดเก็บไว้ในรูป Array)
$cartRows =$_POST["cartRows"];#จำนวน Record ของแถวทั้งหมดของสินค้า(จัดเก็บไว้ในรูป Array)
$pamount=$_POST["pd_amount"];#จำนวน Record ของสินค้า(จัดเก็บไว้ในรูป Array)
for($i=0;$i<=(count($cartRows)-1);$i++){#วนลูปไปทีละแถวเพื่ออัพเดทจำนวนสินค้า
if($pamount[$i]>0){#เอาเฉพาะจำนวนสินค้าที่มากกว่า0
$_SESSION[$cartRows[$i]][1] = $pamount[$i] ; #เซตจำนวนสินค้าใหม่ให้มีค่าเท่ากับจำนวนที่ลูกค้าระบุ
}
}
}
?>
<div>
<h3>ตะกร้าสินค้า</h3>
<?php if(count($_SESSION["cartNumber"])<1){?>
<img src="cart1.gif" width="102" height="82">
<?php }else {?>
<img src="cart2.gif" width="102" height="82">
<?php } ?>
<form name="feditcart" id="feditcart" method="post" action="showcart.php">
<table width="100%" border="0" cellpadding="3" cellspacing="0" style="border:#fff solid 2px;">
<tr bgcolor="#0099FF">
<td width="73%"><strong>ชื่อสินค้า</strong></td>
<td width="11%" align="center"><strong>จำนวน</strong></td>
<td width="7%" align="center"><strong>ราคา</strong></td>
<td width="9%" align="center"><strong>ลบ</strong></td>
</tr>
<?
if(count($_SESSION["cartNumber"])>0){#จำนวนข้อมูลที่มีอยู่หากมากกว่า0
foreach($_SESSION["cartNumber"] as $RowCount){#วนลูปดึงข้อมูลสินค้าออกมาให้ครบตามจำนวนข้อมูลที่มีอยู่
$rs_showpd=mysql_fetch_array(mysql_query("SELECT * FROM product WHERE id_pd=".$_SESSION[$RowCount][0].""));
?>
<tr>
<td height="23"><?=$rs_showpd["name_pd"]#ชื่อสินค้า?>
<input type="hidden" name="cartRows[]" value="<?=$RowCount?>" />
<input type="hidden" name="pd_id[]" value="<?=$rs_showpd["id_pd"]#รหัสสินค้า?>" /></td>
<td align="center"><input name="pd_amount[]" type="text" class="pd_amount" size="5" value="<?=$_SESSION[$RowCount][1]#จำนวนสินค้า?>"/></td>
<td align="center"><?=$TotalPriceAmount=$_SESSION[$RowCount][2]*$_SESSION[$RowCount][1]#ราคาสินค้า?></td>
<td align="center"><a href="#" onclick="delCart(this);return false;" id="<?=$RowCount?>"> <img src="del.gif" width="16" height="16" border="0"></a></td>
</tr>
<?
$TotalAmount+=$_SESSION[$RowCount][1];#คำนวณหาจำนวนสินค้าทั้งหมด
$TotalPrice+=$TotalPriceAmount;#คำนวณหาราคาสินค้าทั้งหมด
}
?>
<tr>
<td height="23" align="right"><strong> รวม</strong></td>
<td align="center"><strong>
<?= $TotalAmount?>
</strong></td>
<td align="center"><strong>
<?= number_format($TotalPrice,2,".",",")?>
</strong></td>
<td align="center"> </td>
</tr>
<tr>
<td height="23" colspan="4" align="center"><a href="#" onclick="alert('ต่อยอดเอาเองเน้อ!!!');">ยืนยันการสั่งซื้อ</a></td>
</tr>
<? } else { ?>
<tr>
<td height="23" colspan="4" align="center"><strong>ไม่พบสินค้าในตระกร้า</strong></td>
</tr>
<? } ?>
</table>
</form>
</div>
ในไฟล์นี้ผมได้ใช้รูป 2 รูป แทนสถานะสินค้าในตะกร้า คือ
ไฟล์ cart1.gif =แสดงเมื่อสินค้าในตะกร้าสินค้าว่างเปล่า
ไฟล์ cart2.gif=แสดงเมื่อมีรายการสินค้าในตะกร้าสินค้า
ผมคงไม่ขออธิบายอะไรแล้วนะครับ เพราะผมได้เขียนคอมเม้นท์เอาไว้แล้ว ลองเอาไปประยุกต์กับระบบตะกร้าสินค้าของคุณดูนะครับ หากสงสัยอะไร สามารถสอบถามผมได้จากช่องคอมเม้นท์ด้านล่างเลยนะครับ


ขอบคุณค่าาา
ตอบลบ^^ เย่ทำได้แล้ว
ตอบลบรบกวนถามนะคะ ถ้าเราอยากให้ showcart.php เลื่อนตามสกอบาร์จะเพิ่มยังไงดีคะ คิดว่าจะเอาฟิกอยู่กับที่ แต่มันคงลำบากมากเวลาจะแดร๊กใส่ อ่าค่ะ
เลยอยากจะให้มันฟิกกับสกอบาร์ไปเลย
คงต้องแก้โค๊ดยาวเลยครับ ลองศึกษาโค๊ดจากในนี้ดูครับ ->http://php-for-ecommerce.blogspot.com/2011/12/add-to-cart-ajax-jquery.html
ลบตัวอย่าง -> http://pluto.host22.com/a2c/showproduct.php
ว้าวว สุดยอดอ่ะค่ะ ขอบคุณมากค่ะ ^^
ตอบลบต้องการบันทึกลง ordersdetail ต้องทำยังงัยครับ
ตอบลบลองนำโค๊ดจากบทความนี้ไปประยุกต์ดูเองนะครับ
ลบhttp://php-for-ecommerce.blogspot.com/2011/01/shopping-cart-2.html
อยากทราบว่ามีการเลือกสินค้ามากกว่า 1 ชิ้น แล้วจะส่งค่า id สิ้นค่าและจำนวนสิ้นค้าที่เลือกแต่ละชิ้น ไปอีกหน้าจะทำด้วยวิธีใดบ้าง เพราะตอนนี้ส่งค่า id สินค้าที่เลือกไปได้แค่ id ล่าสุด id เดียว ขอบคุณค่ะ (พอดีเพิ่งหัดเขียน^_^)
ตอบลบลองศึกษาได้จากบทความของผมเลยครับ ผมได้สอนวิธีเก็บข้อมูลสินค้าที่สั่งซื้อ ด้วย session กับ cookie ด้วยครับ
ลบhttp://php-for-ecommerce.blogspot.com/search/label/%E0%B8%95%E0%B8%B0%E0%B8%81%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%AA%E0%B8%B4%E0%B8%99%E0%B8%84%E0%B9%89%E0%B8%B2%28Shopping%20Cart%29
แนะนำให้ศึกษาบทความนี้เป็นหลักครับ
http://php-for-ecommerce.blogspot.com/2010/12/1-add-to-cart-1-add-to-cart.html
ขอบคุณค่ะ
ลบ