1
votes

I am trying to update a Magento "mini-cart" located in the header using a PHP script that is accessed via an AJAX call.

The cart has both "increment" and "decrement" buttons. When clicked, the PHP script is run and the quantity of a specific product in the cart gets saved and updated.

Now, the problem is that when I run this PHP script, there appear to be no items in the shopping cart. I have looked at the Session IDs on both when I am on the main home page, and when the script is run and they both seem to be different. This is why I think the script seems to believe that I don't have any items in the cart.

I believe the code I have written to get the Session ID and the cart items is correct. Does anyone know what I might be doing wrong here?

Code shown below. I know that this could probably be written better, but for now I just want to see something working!.

The HTML in header.phtml (this is within the loop to get all items in basket - works fine here):

<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>

The AJAX:

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");
                }
            });
        }

The 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;     
};
1

1 Answers

0
votes

You are calling the ajax update function with 2 arguments i.e product id and qty.and you called a function on increment and decrment button called update with only one argument called productid.

you can do one thing.change the ajax update function argument.use only one argument called product id.