1

I am using this below code to add a product to the cart from a phtml file:

<form data-role="tocart-form" action="<?php echo $addToCartUrl; ?>" method="post"> 
    <?php echo $block->getBlockHtml('formkey')?>
    <div class="btn">
        <button type="submit" title="Add to Cart" class="action tocart primary">
            <span>Add to Cart</span>
        </button>
    </div>   
 </form>

But at $addToCartUrl, I receive some extra characters like this:

www.webi.com/checkout/cart/add/uenc/aHR0cHM6Ly93d3cudGliby50di8yMDE4OS9ibGk%2C/product/2/

The part before /product/2/ adds these characters: %2C and in this way, I can't add the product to cart!

2
  • which place you have keep query string product/2? – Rakesh Jesadiya Dec 29 '17 at 11:36
  • that part its ok, but if you look it, before that part, you have the %2C that is added, and that cause my product to not add it to cart. I don't understand why its that part added – Algert Zh Dec 29 '17 at 11:41
2

I am also having this same issue before while tried to add to cart from phtml. So, I try this way which is works fine for me. Try this -

Step 1: (Mention this function under any helper and use scope interface)

use Magento\Store\Model\ScopeInterface;

public function getAddToCartUrl(){ 
        return $this->_storeManager->getStore()->getUrl('checkout/cart/add');
    }

Step 2: (Call this function in your phtml as a from action)

    $_Helper = $this->helper('Custom\Wholesalecart\Helper\Data');

    <form action="<?php echo $_Helper->getAddToCartUrl() ?>" method="post">
       <?php echo $block->getBlockHtml('formkey')?>
       {{Your content here}}
        <button type="submit" title="Add to Cart" class="action tocart primary">
           <span>Add to Cart</span>
        </button>
</form>
2
  • I can try this, but where should I put product ID to add to cart? – Algert Zh Jan 3 '18 at 12:21
  • 1
    Put this <input type="hidden" name="product" value="<?php echo $_product->getId() ?>" /> and qty box like <input name="qty" id="<?php echo $_product->getId() ?>" value="1" title="Qty" class="input-text qty" data-validate="null" type="number"> where i have mentioned "{{Your content here}}" – Indranil Maity Jan 3 '18 at 12:28
0

Use html_entity_decode() to remove unnecessary character encode.

<form data-role="tocart-form" action="<?php echo html_entity_decode($addToCartUrl); ?>" method="post"> 
    <?php echo $block->getBlockHtml('formkey')?>
    <div class="btn">
        <button type="submit" title="Add to Cart" class="action tocart primary">
            <span>Add to Cart</span>
        </button>
    </div>   
 </form>
1
  • Thank you for your answer, but still the same issue. – Algert Zh Dec 29 '17 at 11:55

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.