当选择添加时,使购物车数量计数器显示添加的产品


Getting Shopping cart quanitity counter to show product added right when selected to add

我的网站上有一个购物车数量计数器,在重新加载页面或转到另一个页面之前,它不会显示产品已添加。我想让数量计数器立即显示正在添加的产品。我每页都有这个数量计数器。我确信Ajax可以添加这样的东西,但我甚至不知道如何开始。

我现在把它设置成这样:

我的网站上的每一页都有一个需要的页面,名为loadProducts.php

它持有这个:

//Shopping Cart Quantity Count
    if(isset($_SESSION['shopping_cart']) && is_array($_SESSION['shopping_cart'])) {
    $totalquantity = 0;
    foreach($_SESSION['shopping_cart'] AS $product) {
        $totalquantity = $totalquantity + $product['quantity'];
    }

 }
  else {
       $totalquantity = 0;
  }

有没有一种方法可以在我把东西放进购物车后立即装载?如果你想了解我的意思,我的网站是buyfarbest.com。如果转到"产品"选项卡,然后添加产品。添加后,您必须转到另一个页面才能配置该数量。

您可以使用以下javascript动态请求这些数据。

cartQuantity.php

<?php
$totalQuantity = 0;
$success = false; //If session is not set, leave this as false
if(isset($_SESSION['shopping_cart']) && is_array($_SESSION['shopping_cart'])) {
    foreach($_SESSION['shopping_cart'] AS $product) {
        $totalquantity += $product['quantity']; //Increment total quantity by product quantity 
    }
    $success = true; //Session is set, and quantity has been incremented
}
header('Content-type: application/json'); //jquery will automatically parse what follows as a json array.  Handy!
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
echo json_encode(array('success'=>$success, 'shopping_cart_quantity'=>$totalQuantity));

以及在您的html:中

<div id='shoppingCartCounter'></div>
<script type='text/javascript'>
    function updateCartCounter() {
        $.get('path/to/cartQuantity.php', function(json) {
            var shoppingCartCounter = $('#shoppingCartCounter'); //Make a local variable to reference the appropriate div
            if(json['success']) { shoppingCartCounter.html(json['shopping_cart_quantity']) } //populate it with the count
            else shoppingCartCounter.html(''); //or erase the number altogether
        });
    }
</script>

现在,无论何时调用updateCartCounter(),计数器都会执行此操作。您可以通过以下任一种或两种方式来完成此操作:

有一个间隔(不是很有效)

setInterval(function(){ updateCartCounter(); }, 10000); //Update the counter every 10 seconds

或在您的购物车操作功能内

function someCartOperation() { //This is whatever your application uses for adding/removing stuff in the cart
    /*
        Do all your important cart stuff
    */
    updateCartCounter(); //You're done working on the cart, now update the counter
}