我正在进行Web开发的第一个项目。我正在使用php ajax和jquery。我正在寻找以下问题的解决方案:
当用户点击“添加到购物车”按钮时,应该为该特定用户禁用该产品(产品/“添加到购物车”按钮),直到用户从购物车页面中删除该产品为止。即用户不应该一次又一次地将同一产品添加到购物车中。
这是我的javascript文件“init.js”
('.add_to_cart').on('click dblclick',adding);
//$("body").on(".add_to_cart","click",adding);
function adding(e) {
e.preventDefault();
var prodid =$(this).attr("id");
var that = $(this);
that.off("click dblclick");
$.ajax({
type: "POST",
url: "addcart.php",
data:{prodid:prodid}
}).done(function(msg) {
alert(msg);
}).always(function() {
that.off("click dblclick",adding);
})
};
这是php文件,“addcart.php”
<?php
session_start();
/*if(isset($_SESSION['islogged'])){
if(!isset($_SESSION['username']))
echo "Please log in to add books to your cart";
}
*/
require_once 'connect.inc.php';
if (isset($_POST['prodid'])) {
if (!empty($_POST['prodid'])) {
if (!isset($_SESSION['username'])) {
echo "Please log in to add books to your cart";
} else {
$product_id = $_POST['prodid'];
$username = $_SESSION['username'];
$query = "SELECT * FROM `books1` where `id`='$product_id'";
$query_run = mysqli_query($link, $query);
while ($row = mysqli_fetch_assoc($query_run)) {
$productname = $row['name'];
$productid = $row['id'];
$productauthor = $row['author'];
$productpublication = $row['publication'];
$productcategory = $row['category'];
$productsubcategory = $row['sub_category'];
$productborrowalprice = $row['borrowal price'];
$productimage = $row['image'];
$query1 = "INSERT into `cart`(`user_name`,`p_id`,`p_name`,`p_author`,`p_publication`,`p_category`,`p_subcategory`,`p_borrowalprice`,`p_image`,`qty`)VALUES('$username',$productid,'$productname','$productauthor','$productpublication','$productcategory','$productsubcategory','$productborrowalprice','$productimage',0)";
$result = mysqli_query($link, $query1);
if ($result) {
echo 'successful';
} else {
die(mysqli_error($link));
}
}
}
}
}
?>
答案 0 :(得分:0)
你使用btn.loading和btn.reset。将btn保存为变量以避免范围更改时发生冲突。
$('.add_to_cart').on('click dblclick',adding);
//$("body").on(".add_to_cart","click",adding);
function adding(e) {
var cur = $(this).button("loading");
e.preventDefault();
var prodid =$(this).attr("id");
var that = $(this);
that.off("click dblclick");
$.ajax({
type: "POST",
url: "addcart.php",
data:{prodid:prodid}
}).done(function(msg) {
alert(msg);
}).always(function() {
that.off("click dblclick",adding);
cur.reset()
})
};