0
最初の頃の作品。カートの各項目にはプラス記号とマイナス記号がありますので、ユーザーは1ずつ増やしたり1ずつ減らしたりできます。プラス記号をクリックすると、クリックした特定の項目に1つ追加する必要があります。現在のところ、これは最初にクリックされたもので、その後のクリックでは機能しません。問題がjqueryであるかPHPであるかはわかりません。更新カートの数量は1つのだけのアイテムがカートに追加され、
$("body").on("click", ".cartPlus", function() {
var itemToEdit = $(this).data('id');
var qty = $(this).data('qty');
var newQty = qty + 1;
$.ajax({
url: 'functions/show-cart.php',
type: 'POST',
dataType: 'json',
data: {
itemToEdit: itemToEdit,
newQty: newQty
},
beforeSend: function() {
$(".price-xs").empty();
},
})
.done(function (data) {
$.each(data.cart, function (index, item) {
console.log(item.each_item);
});
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log(textStatus + ': ' + errorThrown);
console.warn(jqXHR.responseText);
});
});
if(isset($_POST['itemToEdit']) && $_POST['itemToEdit'] != "") {
$i = 0;
$item_to_edit = $_POST['itemToEdit'];
$quantity = $_POST['newQty'];
foreach($_SESSION['cart_array'] as $each_item) {
$i++;
while(list($key, $value) = each($each_item)) {
if($key == "item_id" && $value == $item_to_edit) {
array_splice($_SESSION['cart_array'], $i-1, 1, array(array("item_id" => $item_to_edit, "quantity" => $quantity)));
}
}
}
}
if(!isset($_SESSION['cart_array'])) {
$itemsInCart = 0;
$response['total'] = 0;
echo json_encode($response);
} else {
$featured = "Yes";
$i=0;
foreach($_SESSION['cart_array'] as $each_item) {
$item_id = $each_item['item_id'];
$stmt = $link->prepare("SELECT `product_name`, `price`, `pic_name` FROM `products` as `p` INNER JOIN `product_images` as `pi` ON p.`id` = pi.`product_id` WHERE p.`id` = ? AND `featured` = ?");
$stmt->bind_param("is", $item_id, $featured);
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
while($row = $result->fetch_assoc()) {
$product_name = sanitize($row['product_name']);
$price = sanitize(money_format('%.2n', $row['price']));
$subtotal = money_format('%.2n', $each_item['quantity'] * $price);
$pic_name = $row['pic_name'];
$cartTotal = $subtotal + $cartTotal;
$quantity = $each_item['quantity'];
$cart_details[] = array(
"product_name" => $product_name,
"price" => $price,
"subtotal" => $subtotal,
"pic_name" => $pic_name,
"each_item" => $quantity,
"item_id" =>$item_id,
"i" => $i
);
$i++;
}
}
$stmt->close();
}
$response['total'] = $cartTotal;
$response['cart'] = $cart_details;
echo json_encode($response);
}
これは、データ( 'qty')を更新していないため、同じ値を与えるコードで毎回更新されないために発生します。したがって、数量は常に初期値よりも1大きい値になります。 –
私の.done()の直下で更新する必要がありますか? – user8463989
はい、完了したメソッド内で更新する必要があります。 –