0

I have made one custom module. Where i want to show some custom related products on product page.

I select the product with checkbox to add to cart and When i click add to cart, products are added in cart but not shown in shopping cart See

enter image description here

When i refresh the page the products appear in the cart See

enter image description here

This is happening only with my custom module. Default magento functionality works well.

My Controller action code

    <?php

       namespace MagePal\LinkProduct\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 Index 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,
      
            \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->_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);
        print_r($params);
         $product = $this->productFactory->create()->load($productId);
        $this->cart->addProduct($product,$params);

        }
         $this->cart->save();
        
        // $productId=1;
         $result = $this->resultJsonFactory->create();
        return $result->setData($productId);
          
    }

}

Js script

<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 quantity =  $("#quantity").val();
                        product_data = {
                ids: searchIDs,
                qty: quantity
                       }
            var addCartUrl = "<?php echo $baseUrl . 'linkproduct/index/index' ?>";
            
            jQuery.ajax({
                type: 'POST', showLoader: true,
                url: addCartUrl,
                data: {data : JSON.stringify(product_data)}, 
                success: function (data) {
                  
                    console.log(data);
                    

                },
                error: function (request, error)
                {
                    console.log("Error");
                }
            });
            return false;

        });

    }
    );
</script>
1

Add this script to your phtml file

<script>
require(
    [
    'jquery',
    'Magento_Customer/js/customer-data',
    'Magento_Ui/js/modal/modal'
    ],
    function($,customerData) {
        

        $("#submit").click(function(event){
            event.preventDefault();
            var searchIDs = $(".test input:checkbox:checked").map(function(){
                return $(this).val();
}).get(); // <----
            var quantity =  $("#quantity").val();
                        product_data = {
                ids: searchIDs,
                qty: quantity
                       }
            var addCartUrl = "<?php echo $baseUrl . 'linkproduct/index/index' ?>";
            
            jQuery.ajax({
                type: 'POST', showLoader: true,
                url: addCartUrl,
                data: {data : JSON.stringify(product_data)}, 
                success: function (data) {
                    var sections = ['cart'];
                    customerData.invalidate(sections);
                    customerData.reload(sections, true);
                    console.log(data);

                },
                error: function (request, error)
                {
                    console.log("Error");
                }
            });
            return false;

        });

    }
    );
</script>
| improve this answer | |
  • Sorry this did not work – Steven Harris Jun 26 at 11:23
  • have you add this code on your phtml file ? not in js file ok – Msquare Jun 26 at 11:28
  • yes added in phtml file – Steven Harris Jun 26 at 11:30
  • My phtml file contains one more script, so added this script after that. check my post for script – Steven Harris Jun 26 at 11:33
  • please share your code – Msquare Jun 26 at 11:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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