Hi guys,
Im displaying all the product id in phtml,the user needs check Ids and submit, the checked products should add to the cart using Ajax. Everything works fine but Im getting the checked value in the form of array in ajax controller,foreach is not working,only last product is adding to cart
My Code
(Magento 2.3.2)
phtml file
<?php $baseUrl = $block->getBaseUrl(); ?> <ul class="test" > <li><input type="checkbox" value="1">1</li> <li><input type="checkbox" value="2">2</li> <li><input type="checkbox" value="3">3</li> </ul> <button id="submit" >OK</button> <script> require( [ 'jquery', 'Magento_Ui/js/modal/modal' ], function( $ ) { $("#submit").click(function(event){ event.preventDefault(); var searchIDs = $(".test input:checkbox:checked").map(function(){ return $(this).val(); }).get(); // <---- var jsonString = JSON.stringify(searchIDs); var addCartUrl = "<?php echo $baseUrl . 'mofosys_test/index/addtocart/' ?>"; jQuery.ajax({ type: 'POST', showLoader: true, url: addCartUrl, data: {data : jsonString}, success: function (data) { console.log(data); }, error: function (request, error) { console.log("Error"); } }); return false; }); } ); </script>
Ajax controller
<?php namespace Mofosys\Test\Controller\Index; use Magento\Framework\App\Action\Context; use Magento\Framework\View\Result\PageFactory; use Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\App\Action\Action; use Magento\Framework\Data\Form\FormKey; use Magento\Checkout\Model\Cart; use Magento\Catalog\Model\Product; class Addtocart extends \Magento\Framework\App\Action\Action { protected $_resultPageFactory; protected $_customerSessionFactory; protected $resultJsonFactory; protected $cacheTypeList; protected $cacheFrontendPool; protected $_registry; protected $_categoryFactory; protected $_productCollectionFactory;protected $formKey;protected $cart; public function __construct(Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory, JsonFactory $resultJsonFactory, \Magento\Customer\Model\Session $customerSessionFactory, \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList, \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool, \Magento\Catalog\Model\CategoryFactory $categoryFactory, // Registry $registry, \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,FormKey $formKey, Cart $cart, Product $product ) { $this->_resultPageFactory = $resultPageFactory; $this->_customerSessionFactory = $customerSessionFactory; $this->resultJsonFactory = $resultJsonFactory; $this->_cacheTypeList = $cacheTypeList; $this->_cacheFrontendPool = $cacheFrontendPool; // $this->_registry = $registry; $this->_categoryFactory = $categoryFactory; $this->_productCollectionFactory = $productCollectionFactory; $this->formKey = $formKey; $this->cart = $cart; $this->product = $product; parent::__construct($context); } public function execute() { $dataId = json_decode(stripslashes($this->getRequest()->getParam('data'))); foreach ($dataId as $productId) { $params = array( 'form_key' =>$this->formKey->getFormKey(), 'product' => $productId, //product Id 'qty' =>1, //quantity of product ); $product = $this->product->load($productId); $this->cart->addProduct($product, $params); } $this->cart->save(); // $productId=1; $result = $this->resultJsonFactory->create(); return $result->setData($productId); } }
Solved! Go to Solution.
Hello @raju_a ,
In your controller your are using Magento\Catalog\Model\Product, it creates injectible objects. Sor every time you call the $product it returns the same existing one. For this megento provide us Factories. So use Magento\Catalog\Model\ProductFactory instead ofMagento\Catalog\Model\Product. Now whenever you use the product it create an object for you. Please use the below code for your ajax controller:
<?php namespace Mofosys\Test\Controller\Index; use Magento\Framework\App\Action\Context; use Magento\Framework\View\Result\PageFactory; use Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\App\Action\Action; use Magento\Framework\Data\Form\FormKey; use Magento\Checkout\Model\Cart; use Magento\Catalog\Model\ProductFactory; class Addtocart extends \Magento\Framework\App\Action\Action { protected $_resultPageFactory; protected $_customerSessionFactory; protected $resultJsonFactory; protected $cacheTypeList; protected $cacheFrontendPool; protected $_registry; protected $_categoryFactory; protected $_productCollectionFactory;protected $formKey;protected $cart; public function __construct(Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory, JsonFactory $resultJsonFactory, \Magento\Customer\Model\Session $customerSessionFactory, \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList, \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool, \Magento\Catalog\Model\CategoryFactory $categoryFactory, // Registry $registry, \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,FormKey $formKey, Cart $cart, Product $product ) { $this->_resultPageFactory = $resultPageFactory; $this->_customerSessionFactory = $customerSessionFactory; $this->resultJsonFactory = $resultJsonFactory; $this->_cacheTypeList = $cacheTypeList; $this->_cacheFrontendPool = $cacheFrontendPool; // $this->_registry = $registry; $this->_categoryFactory = $categoryFactory; $this->_productCollectionFactory = $productCollectionFactory; $this->formKey = $formKey; $this->cart = $cart; $this->product = $product; parent::__construct($context); } public function execute() { $dataId = json_decode(stripslashes($this->getRequest()->getParam('data'))); foreach ($dataId as $productId) { $params = array( 'form_key' =>$this->formKey->getFormKey(), 'product' => $productId, //product Id 'qty' =>1, //quantity of product ); $product = $this->product->create()->load($productId); $this->cart->addProduct($product, $params); } $this->cart->save(); // $productId=1; $result = $this->resultJsonFactory->create(); return $result->setData($productId); } }
Hope this will help you.
If you to know more about injectable and non-injectible class, please refer the link https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html#newablenon-injectable
If it helps you , please give us kudos and accept it as solution.
Thank you
Hello @raju_a ,
In your controller your are using Magento\Catalog\Model\Product, it creates injectible objects. Sor every time you call the $product it returns the same existing one. For this megento provide us Factories. So use Magento\Catalog\Model\ProductFactory instead ofMagento\Catalog\Model\Product. Now whenever you use the product it create an object for you. Please use the below code for your ajax controller:
<?php namespace Mofosys\Test\Controller\Index; use Magento\Framework\App\Action\Context; use Magento\Framework\View\Result\PageFactory; use Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\App\Action\Action; use Magento\Framework\Data\Form\FormKey; use Magento\Checkout\Model\Cart; use Magento\Catalog\Model\ProductFactory; class Addtocart extends \Magento\Framework\App\Action\Action { protected $_resultPageFactory; protected $_customerSessionFactory; protected $resultJsonFactory; protected $cacheTypeList; protected $cacheFrontendPool; protected $_registry; protected $_categoryFactory; protected $_productCollectionFactory;protected $formKey;protected $cart; public function __construct(Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory, JsonFactory $resultJsonFactory, \Magento\Customer\Model\Session $customerSessionFactory, \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList, \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool, \Magento\Catalog\Model\CategoryFactory $categoryFactory, // Registry $registry, \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,FormKey $formKey, Cart $cart, Product $product ) { $this->_resultPageFactory = $resultPageFactory; $this->_customerSessionFactory = $customerSessionFactory; $this->resultJsonFactory = $resultJsonFactory; $this->_cacheTypeList = $cacheTypeList; $this->_cacheFrontendPool = $cacheFrontendPool; // $this->_registry = $registry; $this->_categoryFactory = $categoryFactory; $this->_productCollectionFactory = $productCollectionFactory; $this->formKey = $formKey; $this->cart = $cart; $this->product = $product; parent::__construct($context); } public function execute() { $dataId = json_decode(stripslashes($this->getRequest()->getParam('data'))); foreach ($dataId as $productId) { $params = array( 'form_key' =>$this->formKey->getFormKey(), 'product' => $productId, //product Id 'qty' =>1, //quantity of product ); $product = $this->product->create()->load($productId); $this->cart->addProduct($product, $params); } $this->cart->save(); // $productId=1; $result = $this->resultJsonFactory->create(); return $result->setData($productId); } }
Hope this will help you.
If you to know more about injectable and non-injectible class, please refer the link https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html#newablenon-injectable
If it helps you , please give us kudos and accept it as solution.
Thank you
Hello @raju_a ,
Are you still facing the same issue ?
Thank you very much ,it worked
<?php namespace Mofosys\Test\Controller\Index; use Magento\Framework\App\Action\Context; use Magento\Framework\View\Result\PageFactory; use Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\App\Action\Action; use Magento\Framework\Data\Form\FormKey; use Magento\Checkout\Model\Cart; // use Magento\Catalog\Model\Product; use Magento\Catalog\Model\ProductFactory; class Addtocart extends \Magento\Framework\App\Action\Action { protected $_resultPageFactory; protected $_customerSessionFactory; protected $resultJsonFactory; protected $cacheTypeList; protected $cacheFrontendPool; protected $_registry; protected $_categoryFactory; protected $_productCollectionFactory; protected $formKey;protected $cart; protected $productFactory; public function __construct(Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory, JsonFactory $resultJsonFactory, \Magento\Customer\Model\Session $customerSessionFactory, \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList, \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool, \Magento\Catalog\Model\CategoryFactory $categoryFactory, // Registry $registry, \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,FormKey $formKey, Cart $cart, // Product $product ProductFactory $productFactory ) { $this->_resultPageFactory = $resultPageFactory; $this->_customerSessionFactory = $customerSessionFactory; $this->resultJsonFactory = $resultJsonFactory; $this->_cacheTypeList = $cacheTypeList; $this->_cacheFrontendPool = $cacheFrontendPool; // $this->_registry = $registry; $this->_categoryFactory = $categoryFactory; $this->_productCollectionFactory = $productCollectionFactory; $this->formKey = $formKey; $this->cart = $cart; // $this->product = $product; $this->productFactory = $productFactory; parent::__construct($context); } public function execute() { // $categoryIdAjax = $this->getRequest()->getParam('catId'); // $optionValueAjax = $this->getRequest()->getParam('optionValue'); $dataId = json_decode(stripslashes($this->getRequest()->getParam('data'))); foreach ($dataId as $productId) { $params = array( 'form_key' =>$this->formKey->getFormKey(), 'qty' =>3, //quantity of product ); // $product = $this->productFactory->load($dataId); $product = $this->productFactory->create()->load($productId); $this->cart->addProduct($product,$params); } $this->cart->save(); // $productId=1; $result = $this->resultJsonFactory->create(); return $result->setData($dataId); } }
Hello,
How can we add dynamic quantity here??
Hello,
With the help of Magento 2 Ajax add to cart extension customers can easily add multiple products to the cart.
Learn here about:- How to add Product to Cart Using Ajax Programmatically in Magento 2