簡體   English   中英

Magento AJAX 購物車數量更新。 購物車中沒有商品

[英]Magento AJAX cart quantity update. No items in cart

我正在嘗試使用通過 AJAX 調用訪問的 PHP 腳本更新位於標題中的 Magento“迷你購物車”。

購物車有“增加”和“減少”按鈕。 單擊后,將運行 PHP 腳本並保存和更新購物車中特定產品的數量。

現在,問題是當我運行這個 PHP 腳本時,購物車中似乎沒有商品。 我在主頁上和腳本運行時都查看了會話 ID,它們似乎都不同。 這就是為什么我認為腳本似乎相信我的購物車中沒有任何物品。

我相信我為獲取會話 ID 和購物車項目而編寫的代碼是正確的。 有誰知道我在這里可能做錯了什么?

代碼如下所示。 我知道這可能會寫得更好,但現在我只想看到一些工作!

header.phtml 中的 HTML(這是在循環中獲取籃子中的所有項目 - 在這里工作正常):

<button id="decrement" onclick="updateCart(<?php echo $product->getId(); ?>);" class="decrement">-</button>
<input type="text" class="quantity" name="quantity" id="quantity" value="<?php echo $product->getQty(); ?>">
<button id="increment" onclick="updateCart(<?php echo $product->getId(); ?>);" class="increment">+</button>

阿賈克斯:

function updateCart(productId, qty) {
            qty = jQuery('#quantity').val()
            jQuery.ajax({
                type: "POST",
                dataType: "HTML",
                data: { productId : productId, qty : qty },
                url: "scripts/get_cart_script.php?productId=" + productId + "&qty=" + qty,
                success: function (data) {
                    alert("Success");

                },
                error: function(data){
                    alert("Failure");
                }
            });
        }

PHP:

require_once  $_SERVER['DOCUMENT_ROOT'] . '/app/Mage.php';

Mage::app();

// Get session
Mage::getSingleton('core/session', array('name'=>'frontend'));

// Check for a product id
if(isset($_REQUEST['productId']))
{

    // Product ID and Quantity
    $pid = $_REQUEST['productId'];
    $qnt = $_REQUEST['qty'];

    $cart = Mage::getSingleton('checkout/cart');
    $items = $cart->getItems(); 

    foreach ($items as $item) :
        if($pid == $item->getId()) :
            echo $item->getQty();
            $item->setQty($qnt); 
            $cart->save();
        endif;
    endforeach;     
};

您正在使用 2 個參數(即產品 ID 和數量)調用 ajax 更新函數,並且您調用了一個名為 update 的增量和減量按鈕的函數,只有一個名為 productid 的參數。

您可以做一件事。更改 ajax 更新函數參數。僅使用一個名為產品 ID 的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM