1

I have some buttons that onclick on them work with two Ajax requests that add and remove products, but this is not of extreme importance in this matter. My problem is this: if the buy button is clicked, the product is added, but if the page is updated it will be there, but I can only have one product the same at a time and if after the updated page the button buy is clicked again, another product is added and this can not happen, because what is already added must be removed from the removeCartaotoCart function so that the new one is added so that I have only one product at a time.

What I am not able to do is treat this exception: If the user add a product, refresh the page and he clicks the buy button again, another product is added to the cart, however I can only have one product at a time.

Button code:

<button style="margin-left: 11%;" type="button" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Add to Cart')) ?>" class="button btn-cart" onclick="addCartao('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>" id="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
<button style="display: none; margin-left: 11%;" type="button" id="cartaoMensagemRemover<?php echo $_product->getId(); ?>" title="Remover" class="button btn-cart" onclick="removeCartaotoCart('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span>Remover</span></span></button>

Ajax requisition code:

    var productSelected = "";

    function addCartao(product_id){
        if( productSelected != "" ){
            removeCartaotoCart(productSelected);    // Remove the item in cart, if there is one.
          }
        $j('#cartaoMensagem'+product_id).hide();
        $j('#cartaoMensagemRemover'+product_id).show();
        $j('#cartaoMensagemRemover'+product_id).css({'background-color': '#000000'});
        $j.ajax({
          type: "POST",
          url: "<?php echo Mage::getUrl('fol_carousel/ajax/addCartao') ?>",
          data: {
            product_id: product_id
          },
          dataType: 'json',
          cache : false,
          beforeSend: function () {

          },
          success: function (retorno) {
            var button = $j('#cartaoMensagemRemover'+product_id);
            productSelected = product_id;   
            $j('.item-custom').append('<tr id="trAppend'+product_id+'"><td class="a-center lc-thumbnails"><img src="' + retorno['imagem'] + '" width="50" height="50" alt="' + retorno['name'] + '"></td><td><h3 class="product-name">' + retorno['name'] + '</h3></td><td class="a-center">1</td><td class="a-right"><span class="cart-price"><span class="price"> R$ ' + retorno['price'] + '</span></span></td></tr>');
            getSubTotal();
            getGrandTotal();
          },
          complete: function () {

          },
          error: function (x,y,z) {
            alert("error");
            alert(x);
            alert(y);
            alert(z);
            window.location.reload();
            history.go(0);
            window.location.href=window.location.href;
          }
      });
    }

    function removeCartaotoCart(itemId){
        productSelected = ""; 
        $j('#cartaoMensagemRemover'+itemId).hide();
        $j('#cartaoMensagem'+itemId).show();
        $j.ajax({
            type:"POST",
            url:"<?php echo Mage::getUrl('fol_carousel/ajax/removeCartao') ?>",
            data:{
                itemId: itemId
            },
            cache: false,
            beforeSend: function(){

            },
            success: function(retorno){
                var button = $j('#cartaoMensagemRemover'+itemId);  
                $j('.item-custom #trAppend'+itemId+'').remove();
                getSubTotal();
                getGrandTotal();
            },
            complete: function () {

            },
            error: function (x,y,z) {
            alert("error");
            alert(x);
            alert(y);
            alert(z);
            window.location.reload();
            history.go(0);
            window.location.href=window.location.href;
          }
        });
    }

Note: I would require that in the update of the page, if there is a product, it is already removed from the cart, and the removeCartaotoCart function can be used.

  • Did you write the module behind route fol_carousel/ajax/addCartao? If so, or if you have backend knowledge/access to edit, you would have to update its controller to clear the cart before adding a new product. If you can confirm this is the desired effect, I can give you some sample code that would need to be part of the addCartao endpoint to clear the cart first. – Rick Buczynski Sep 7 '17 at 0:42
  • @RickBuczynski Yes, that's what you said. And I have also got knowledge / access to the backend to make the necessary edits. – Matheus Portela Sep 8 '17 at 16:16
  • Ok, answer coming up shortly. – Rick Buczynski Sep 8 '17 at 17:03
1

There are a couple of ways to approach this, both which involve a modification to your controller on the backend.

Here's the rough procedure:

  1. Remove removeCartaotoCart JavaScript function (not needed)
  2. Update controller method at endpoint fol_carousel/ajax/addCartao
  3. Change your AJAX parameter name from product_id to product

Option A: Clear Cart Contents on Add to Cart

Edit your controller, so that it looks something like this:

<?php

require_once Mage::getModuleDir('controllers', 'Mage_Checkout') . DS . 'CartController.php';

class Your_Module_AjaxController
    extends Mage_Checkout_CartController
{
    private function _sendResponse(Mage_Catalog_Model_Product $product)
    {
        $this->getResponse()
            ->setHeader('Content-Type', 'application/json')
            ->setBody($product->toJson())
            ->sendResponse();

        exit;
    }

    public function addCartaoAction()
    {
        $cart = $this->_getCart();

        $cart->truncate();

        $product = $this->_initProduct();

        $cart->addProduct($product, array('qty' => 1));
        $cart->save();

        $this->_getSession()->setCartWasUpdated(true);

        Mage::dispatchEvent('checkout_cart_add_product_complete',
            array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
        );

        $this->_sendResponse($product);
    }
}

Option B: Clear Item in Cart if Exists on Add to Cart

<?php

require_once Mage::getModuleDir('controllers', 'Mage_Checkout') . DS . 'CartController.php';

class Your_Module_AjaxController
    extends Mage_Checkout_CartController
{
    private function _sendResponse(Mage_Catalog_Model_Product $product)
    {
        $this->getResponse()
            ->setHeader('Content-Type', 'application/json')
            ->setBody($product->toJson())
            ->sendResponse();

        exit;
    }

    public function addCartaoAction()
    {
        $cart   = $this->_getCart();
        $quote  = $this->_getQuote(); 

        $product = $this->_initProduct();

        foreach ($quote->getAllItems() as $item) {
            if ($item->representProduct($product)) {
                $quote->removeItem($item->getId());
            }
        }

        $cart->addProduct($product, array('qty' => 1));
        $cart->save();

        $this->_getSession()->setCartWasUpdated(true);

        Mage::dispatchEvent('checkout_cart_add_product_complete',
            array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
        );

        $this->_sendResponse($product);
    }
}

Option C: Cancel Addition if Exists in Cart

<?php

require_once Mage::getModuleDir('controllers', 'Mage_Checkout') . DS . 'CartController.php';

class Your_Module_AjaxController
    extends Mage_Checkout_CartController
{
    private function _sendResponse(Mage_Catalog_Model_Product $product)
    {
        $this->getResponse()
            ->setHeader('Content-Type', 'application/json')
            ->setBody($product->toJson())
            ->sendResponse();

        exit;
    }

    public function addCartaoAction()
    {
        $cart   = $this->_getCart();
        $quote  = $this->_getQuote(); 

        $product = $this->_initProduct();
        $canAdd  = true;

        foreach ($quote->getAllItems() as $item) {
            if ($item->getProductId() == $product->getId()) {
                $canAdd = false;
                break;
            }
        }

        if ($canAdd) {
            $cart->addProduct($product, array('qty' => 1));
            $cart->save();

            $this->_getSession()->setCartWasUpdated(true);

            Mage::dispatchEvent('checkout_cart_add_product_complete',
                array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
            );

            $this->_sendResponse($product);
        } else {
            // Optional error handling sample
            die('{"error":"Product already in cart."}');
        }

    }
}

Notes:

  • I am extending from another controller, this is important.
  • You must change your AJAX request parameter from product_id to product.
  • The key to Option A is the call to first truncate()
  • The key to Option B is the call to representProduct()

I don't have your controller code so I'm writing my own sample from scratch, but either of these can be adapted to your needs.

| improve this answer | |
  • I made the necessary changes, however it only returns me error 500. – Matheus Portela Sep 8 '17 at 17:48
  • Must be a syntax error in my code, I will test it for myself. Also try to turn on developer mode in index.php to see what it tells you. – Rick Buczynski Sep 8 '17 at 17:52
  • If you want or need it, I update the question with my current controller that I use so you can get an idea. – Matheus Portela Sep 8 '17 at 17:57
  • I just fixed the error, was in the require_once statement. See my updated answer. – Rick Buczynski Sep 8 '17 at 17:58
  • It worked out right now. Thank you very much for all your help and attention! – Matheus Portela Sep 8 '17 at 18:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.