3

Hello Magento 2 Friends.

I have an ajax call to an controller, which adds some new products to the cart programmatically. This works fine, but the problem is that the cart and the mini cart are only refreshed after reloading page. Is there any code I can add, so I don't need to reload the page?

This is my ajax call:

jQuery.ajax({
  type: "POST",
  url: myurl,
  data: {
    productIds: response._productId,
    amounts: response._amount,
  },
  success: function (data){
    console.log(data);
  },
  error: function(data, data1){
    console.log(data);
  },
});

Controller.php

<?php

namespace MassiveArt\ShoppingCart\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\Product;

class Index extends Action
{
    /**
     * @var FormKey
     */
    protected $formKey;

    /**
     * @var Session
     */
    protected $checkoutSession;

    /**
     * @var Cart
     */
    protected $cart;

    /**
     * @var Product
     */
    protected $product;

    /**
     * Constructor.
     *
     * @param Context $context
     * @param \Magento\Checkout\Model\Session $checkoutSession
     * @param \Magento\Customer\Model\Session $customerSession
     * @param JsonFactory $resultJsonFactory
     * @param FormKey $formKey
     * @param Cart $cart
     * @param Product $product
     */
    public function __construct(
        Context $context,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Customer\Model\Session $customerSession,
        JsonFactory $resultJsonFactory,
        FormKey $formKey,
        Cart $cart,
        Product $product
    ) {
        $this->checkoutSession = $checkoutSession;
        $this->customerSession = $customerSession;
        $this->formKey = $formKey;
        $this->resultJsonFactory = $resultJsonFactory;
        $this->cart = $cart;
        $this->product = $product;
        parent::__construct($context);
    }

    public function execute()
    {

        try {

            // Set result data and pass back
            $result = $this->resultJsonFactory->create();

            if(!$this->customerSession->getCustomer()->getId()) {
                $result->setData(['error' => __('Invalid session ID')]);
            }



            // Get parameters
            $productIds = $this->getRequest()->getParam('productIds');
            $amounts = $this->getRequest()->getParam('amounts');

            for ($i = 0; $i < count($productIds); $i++) {// Load product by ID
                $product = $this->product->load($productIds[$i]);
                // New product params
                $params = array(
                    'form_key' => $this->formKey->getFormKey(),
                    'product' => $productIds[$i],
                    'qty'   => $amounts[$i],
                );


                // Save Product
                $product->save();

                // Add product to cart
                $this->cart->addProduct($product, $params);
            }

            //Save cart
            $this->cart->save();

            $result->setData(['message' => __("Products added succesfully")]);

            return $result;
        } catch(\Exception $e) {
            $result->setData(['error' => __($e->getMessage())]);
            return $result;
        }
    }
}

Thanks in advance!

3

As you might know mini cart renders from local storage. So after performing ajax request you need to reload mini cart to update qty. For that you need to create section.xml file.

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

If you don't have controller still you can reload cart from your template file by using below code.

require([
           'Magento_Customer/js/customer-data'
        ], function (customerData) {
            var sections = ['cart'];
            customerData.invalidate(sections);
            customerData.reload(sections, true);
        });

Fore more you can read this. https://webkul.com/blog/update-mini-cart-magento2/

  • Thanks for your help, the minicart gets refreshed now, but the main cart is still not refreshing. Any ideas? – Felix Schönherr Aug 22 at 8:37
  • Where you are performing ajax request ? I mean which page at frontend. – Vivek Aug 22 at 8:41
  • I perform the ajax Request directly in the cart view frontend. Could this be the problem? – Felix Schönherr Aug 22 at 8:43
  • You mean when cart page opens up your ajax will perform ? – Vivek Aug 22 at 8:45
  • 1
    Ok, thanks a lot. Yes after reload everything works. I will try some other stuff. – Felix Schönherr Aug 22 at 8:58

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.