Magento 2 ajax add to cart in Custom Module

Sometime wheb building Mangento Extensions or do the projects in Mangento , you want to add products to cart from list without go to product page. In order to do it you, can use ajax to build the function. In my example , I will make function ajax add to cart from list in custom module.

In order to add to cart use Ajax, you can do the 3 steps bellow:
– Get list Products.
– Create Ajax function.
– Create controller function.

1. Get List products.

You can get list product from Magento Products Collection. You should create custom Block to get Products . For example : create file app/code/Vendor/Module/Block/Products.php

<?php
#file p/code/Magebay/Hello/Block/Products.php 
/**
 * Created by PhpStorm.
 * User: maiuoc
 * Date: 2019-02-22
 * Time: 3:42 PM
 */

namespace Magebay\Hello\Block;


use Magento\Framework\View\Element\Template;

class Products extends \Magento\Framework\View\Element\Template
{
    protected $collectionFactory;
    public function __construct(
        Template\Context $context,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory,
        array $data = []
    )
    {
        parent::__construct($context, $data);
        $this->collectionFactory = $collectionFactory;
    }
    function getCustomProducts() {
        $collection = $this->collectionFactory->create()
            ->addAttributeToFilter('status',1);
        return $collection;
    }
}

Now, We will show list products in phtml file . Create file
app/code/Vendor/Module/view/frontend/templates/products.phtml

<!--file  
app/code/Magebay/Hello/view/frontend/templates/products.phtml -->
<?php if(count($products)) : ?>
<ul>
<?php foreach ($products as $product) : ?>
<li><?php echo $product->getTitle() ?></li>
<li><button id="product-item-<?php echo $product->getId() ?>" class="product-item"></button> </li>
<?php endforeach; ?>
</ul>
<input type="hidden" id="add-cart-url" value="<?php echo $block->getUrl('hello/index/addToCart'); ?>">
<?php endif; ?>

Now, you can see list procucts in fontend , To continue , I will build ajax function use Jquery.

2. Crate ajax function

you can add Jquery code bellow list products in products.phml. The ajax function will call to controller addToCart

<script>
require(['jquery'],function(e){
$('.product-item').click(function(){
var productId = $(this).attr('id');
productId = productId.replace('product-item-','');
var data = {product: productId};
var addToCartUrl = $('#add-cart-url').val();
$.ajax({
url : addToCartUrl,
dataType : 'json',
type : 'POST',
data: data,
success : function(res)
{
console.log('Success');
},
error : function()
{
$console.log('error');
}
});
})
})
</script>

3. Create controller action

As you can see, the ajax function call to addToCart action so I will create new Controller action in
app/code/Vendor/Module/Controller/Index/.php

<?php
/**
* Created by PhpStorm.
* User: maiuoc
* Date: 2019-01-19
* Time: 1:16 PM
*/

namespace Magebay\Hello\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\Controller\Result\JsonFactory;

/**
* Class DellPost
* @package Magebay\Hello\Controller\Index
*/
class AddToCart extends \Magento\Framework\App\Action\Action
{
/**
* Result page factory
*
* @var \Magento\Framework\Controller\Result\JsonFactory;
*/
protected $_resultJsonFactory;
protected $formKey;
protected $cart;
protected $product;
/**
* @param Context $context
* @param PageFactory $resultPageFactory
*/
public function __construct(
Context $context,
JsonFactory $resultJsonFactory,
\Magento\Framework\Data\Form\FormKey $formKey,
\Magento\Checkout\Model\Cart $cart,
\Magento\Catalog\Model\Product $product
)
{
parent::__construct($context);
$this->_resultJsonFactory = $resultJsonFactory;
$this->formKey = $formKey;
$this->cart = $cart;
$this->product = $product;
}
public function execute()
{
$resultJson = $this->_resultJsonFactory->create();
$response = array(
'status'=>'error',
'message'=>'Error, Please try again'
);
$params = $this->getRequest()->getParams();
$productId = isset($params['product']) ? (int)$params['product'] : 0;
if($productId > 0)
{
try {
$params['form_key'] = $this->formKey->getFormKey();
$_product = $this->product->load($productId);
$this->cart->addProduct($_product, $params);
$this->cart->save();
}
catch(\Exception $e) {
$response['message'] = $e->getMessage();
}
}

return $resultJson->setData($response);
}
}

As you can see, you can easy add product to cart by ajax , I hope it is useful for you when Create Module or do the project or website in Mangento. We have a some Great extension like Magento Reservation and Booking System Pro, Magento Multi Vendor Marketplace extension , Magento Product Designer Canvas , if you want to use extensions or build projects in Magento, you can contact to support@magebay.com