I want to add more products to cart using ajax in magento 2 but it doesn't work. please help me to solve this problem here's my code
file ajax.phtml
<script>
require(['jquery'], function($){
$(document).on("click",".tool-buttton-buy", function() {
var addCartUrl = "<?php echo $block->getAjaxUrl().'ajaxcart/index/allcart' ?>";
var searchIDs = $("input[name='product']").map(function(){return $(this).val();}).get();
var jsonString = JSON.stringify(searchIDs);
$.ajax({
url: addCartUrl,
type: 'POST',
showLoader: true,
cache: false,
dataType: 'json',
data: {productId : jsonString},
success: function (data) {
console.log(data);
}
});
})
})
file Controller Ajax
$productAllId = json_decode($this->getRequest()->getParam('productId'));
foreach ($productAllId as $productId) {
$params = array(
'form_key' => $this->formKey->getFormKey(),
'product' => $productId,
'qty' =>1
);
$product = $this->product->load($productId);
$this->cart->addProduct($product, $params);
$this->cart->save();
}