Magento – Add to Cart button in Magento 2.1

addtocartcartmagento-2.1magento2product

I tried with button add to cart and it not working,

app/code/Moo/Custom/view/product.phtml

<?php 
$product = $this->getData('product');
$postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper');
$postData = $postDataHelper->getPostData($block->getAddToCartUrl($product),
['product' => $product->getEntityId()]);

<button class="action description-button" data-post='<?php echo $postData; ?>'
<type="button" title="<?php echo __('Add to cart') ?>">
    <span><?php echo __('Add to cart') ?></span>
</button>

data-post button have action is null ? It look like :

data-post="{"action":null,"data":{"product":"7","uenc":"aHR0cDovLzUyLjE4My4yNi45OC9hcmR6YW5fc3VwZXJtYXJrZXQvaW5kZXgvbG9hZHByb2R1Y3Qv"}}"

Please help me, why it not work?

Best Answer

Create form in your template file and pass action for the same .Also you need to pass formkey .

Try below code :

<form  data-role="tocart-form" action="<?php echo $block->getAddToCartUrl($_item); ?>" method="post">            
<?php echo $block->getBlockHtml('formkey'); ?>
<button type="submit" title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>" class="action tocart primary" style="float:right;margin-left: 10px;">
<span><?php /* @escapeNotVerified */echo __('Add to Cart'); ?></span>
</button>
</form>