2

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.

17
  • can you add namespace in above controller to see where you are at them moment? what is the issue you are facing ? Commented Jan 22, 2019 at 8:25
  • Is it working for you? Commented Jan 22, 2019 at 9:23
  • 1
    @RohanHapani, i am trying it now Commented Jan 22, 2019 at 9:26
  • I have updated controller as per your logic. Please check my answer for more information Commented Jan 22, 2019 at 10:33
  • Did you check with my updated controller code ? Commented Jan 22, 2019 at 13:09

3 Answers 3

3

Replace your controller with below code

 use Magento\Framework\Controller\ResultFactory;
 use Magento\Framework\App\Action\Action;
 use Magento\Framework\App\Action\Context;

/**
 * Responsible for loading page content.
 *
 * This is a basic controller that only loads the corresponding layout file. It may duplicate other such
 * controllers, and thus it is considered tech debt. This code duplication will be resolved in future releases.
 */
class AddItems extends \Magento\Framework\App\Action\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\ProductFactory $product,
        array $data = []
    ) {
        $this->formKey = $formKey;
        $this->cart = $cart;
        $this->product = $product;      
        parent::__construct($context);
    }

    public function execute()
    { 
       $selectedItems = $this->getRequest()->getPost('selectedItems');      
        $selectedItems = explode(",",$selectedItems);
        try{
        foreach ($selectedItems as $key => $selectedItem) {

            $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product_id' => $selectedItem, //product Id
                'qty'   =>1 //quantity of product                
            );
            $_product = $this->product->create()->load($selectedItem);       
            $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;
    }
}

Remove generated folder.

Please check it and let me know in the case of any issue

3
  • for me quote id not retrieved when inserted first time. Commented May 10, 2019 at 12:12
  • hello @Saneer, I am facing problem, when setting custom price for each product Commented May 10, 2019 at 14:07
  • hi @Saneer, i need to store quoteid in my custom table with product id, but i am getting quoteid as empty here,magento.stackexchange.com/questions/274172/… Commented May 13, 2019 at 6:31
2

Add this below code in your controller :

protected $formKey;
protected $_productFactory;
protected $_cart;
protected $messageManager;
public function __construct(
    Context $context,
    \Magento\Framework\Data\Form\FormKey $formKey,
    \Magento\Framework\Message\ManagerInterface $managerInterface,
    \Magento\Catalog\Model\ProductFactory $productFactory,
    \Magento\Checkout\Model\Cart $cart
) {
    parent::__construct($context);
    $this->formKey = $formKey;
    $this->_productFactory = $productFactory;
    $this->_cart = $cart;
    $this->messageManager = $managerInterface;
}

public function execute()
{
    $selectedItems = $this->getRequest()->getPost('selectedItems');      
    //$cart_product = your product data collection or 
    $cart_product = $this->_productFactory->create()->getCollection()->addAttributeToFilter('entity_id',array($selectedItems));

    if ($cart_product) {
        foreach ($cart_product as $key => $value) {
            $custom_optinons_value = '';
            if (isset($value['super_attribute']) || !empty($value['super_attribute'])) {
                $custom_optinons_value = $value['super_attribute'];
            }
            $this->addCartProduct($value['id'], $value['qty'], $custom_optinons_value);
        }
        $this->_cart->save();
    }
    $this->messageManager->addSuccess('Shopping cart updated succesfully.');
}

public function addCartProduct($productID, $productQty, $config_options)
{
    $product = $this->_productFactory->create()->load($productID);
    $info = new \Magento\Framework\DataObject(
        [
            'form_key' => $this->formKey->getFormKey(),
            'product_id' => $productID,
            'qty' => $productQty,
            'super_attribute' => $config_options,
        ]
    );
    return $this->_cart->addProduct($product, $info);
}

Create sections.xml at app/code/VendorName/Abc/etc/frontend

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
    <action name="abc/index/addtocart">
        <section name="cart"/>
    </action>
</config>

Controller path : VendorName/Abc/Controller/Index/Addtocart.php

remove var and generated folder.

12
  • i am not cleared with super attribute and section.xml file Commented Jan 22, 2019 at 9:31
  • sections.xml for add product to cart without page load and super_attribute is for that if custom options available in product then it will also add to cart. In my code, i set like if custom option available then custom option also add. Otherwise, as normal way as like simple product, procedure will be run. Commented Jan 22, 2019 at 9:33
  • will it call same controller from ajax?, can you update me as per my code above Commented Jan 22, 2019 at 9:35
  • Yes. Just copy my controller code into your controller and add your controller action in your sections.xml Commented Jan 22, 2019 at 9:36
  • 1
    I am getting getting internal server error @Rohan Commented Jan 22, 2019 at 11:15
0

I just add 20 sentes. When you use \Magento\Checkout\Model\Cart and method public function addProduct($productInfo, $requestInfo = null)

And your wishes are adding some simples products as coupled on one configurable then don't forget to use only product object for $productInfo with clone: $this->_cart->addProduct(clone $product, $params);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.