I am implementing add to cart functionality from ajax using product id.
This is my code of template file
<tr class="border_bottom child-items selected">
<td >11</td>
<td>Test 2</td>
</tr>
<tr class="border_bottom child-items selected">
<td >12</td>
<td>Test 2</td>
</tr>
<script>
var selectedItems = [];
jQuery("#table tr.selected").each(function(){
selectedItems.push(jQuery('td:first', this).html());
});
var additemUrl = "<?php echo $this->getUrl().'product/addproduct/additems' ?>";
jQuery.ajax({
url: additemUrl,
type: "POST",
data : 'selectedItems='+selectedItems,
dataType: 'json',
success : function(result) {
console.log('success');
}
});
</script>
Here is my controller file.
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
class AddItems extends Action {
protected $formKey;
protected $cart;
protected $product;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Data\Form\FormKey $formKey,
\Magento\Checkout\Model\Cart $cart,
\Magento\Catalog\Model\Product $product,
array $data = []) {
$this->formKey = $formKey;
$this->cart = $cart;
$this->product = $product;
parent::__construct($context);
}
public function execute()
{
$selectedItems = $this->getRequest()->getPost('selectedItems');
echo '<pre>';
print_r($selectedItems);exit;
try{
$params = array(
'form_key' => $this->formKey->getFormKey(),
'product' => $selectedItems, //product Id
'qty' =>1 //quantity of product
);
//Load the product based on productID
$_product = $this->product->load($selectedItems);
$this->cart->addProduct($_product, $params);
$this->cart->save();
$status = 1;
}
catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addException(
$e,
__('%1', $e->getMessage())
);
$status = 0;
} catch (\Exception $e) {
$this->messageManager->addException($e, __('error.'));
$status = 0;
}
$result = array();
$result['status'] = $status;
$resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
$resultJson->setData($result);
return $resultJson;
}
}
Here i need to read each element from the selectedItems array and add to cart. How this can be implemented.
If only item passed from the ajax , I need to add only one item to the cart.
Can anyone help me on this issue please.
Best Answer
Replace your controller with below code
Remove generated folder.
Please check it and let me know in the case of any issue