How to update mini cart quantity in Magento 2 via AJAX?

AJAX technology allows you to update information on your page, without reloading the full page. It speeds up website performance and makes the shopping process smoother. For example, we’ve used this technology in our AJAX Shopping Cart extension. This plugin enables AJAX cart popup with information about added items, their quantity, cart subtotal, related, or cross-sell products.

How to use AJAX to update Magento 2 mini cart quantity?

If you want to update Magento 2 mini cart quantity with ajax, then you need to follow these steps:
Step 1. Create the Amasty/Cart/etc/frontend/sections.xml file and define the controller path.
Step 2. Create a new JS file where you need to update the mini cart.
Step 3. Create the Magento 2 AJAX controller file itself.
The Magento 2 update cart quantity with ajax process is complex and requires technical knowledge as you will need to use some code to implement the needed functionality. Code examples with detailed steps on how to use AJAX to update cart quantity are waiting for you below. Let’s start.

Warning: The code below is an example of how it may look like. Please, customize it according to your business needs.

How does Magento 2 AJAX cart update work?

Magento 2 AJAX cart update works like this: you need to create a controller for the customer data section. It will update the Magento 2 AJAX cart automatically whenever a customer adds something to it. Here’s how it works. When any AJAX request gets complete on DOM, it looks for the selection that needs to be updated. If the section is there, the system reloads it.

Here’s how it works. When any AJAX request gets complete on DOM, it looks for the selection that needs to be updated. If the section is there, the system reloads it.

Step 1. First of all, create the Amasty/Cart/etc/frontend/sections.xml file and define the controller path.

<?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="amcart/ajax/cartUpdate">
<section name="cart"/>
</action>
</config>

 

Step 2. Next, create a new JS file where you need to update the mini cart. For example, like this:

define([
'jquery',
'uiComponent',
'mage/validation',
'ko',
'mage/storage',
'mage/url',
'mage/cookies'
], function ($, Component, validation, ko, storage, urlBuilder) {
'use strict';
return Component.extend({
defaults: {
template:'Amasty_Cart/update_qty'
},

initialize: function () {
this._super();
},
updateMinicart: function () {
this._ajax('amcart/ajax/cartUpdate', {
item_id: 85,
item_qty: 2
});
},
/**
* @param {String} url - ajax url
* @param {Object} data - post data for ajax call
* @param {Object} elem - element that initiated the event
* @param {Function} callback - callback method to execute after AJAX success
*/
_ajax: function (url, data) {
$.extend(data, {
'form_key': $.mage.cookies.get('form_key')
});
$.ajax({
url: urlBuilder.build(url),
data: data,
type: 'post',
dataType: 'json',
context: this,
}).done(function (response) {
alert('you updated checkout cart successfully.')
})
.fail(function (error) {
console.log(JSON.stringify(error));
});
},
});
}
);

Step 3. Finally, create the Magento 2 AJAX controller file itself, like this:

Amasty/Knockout/Controller/Ajax/CartUpdate.php
<?php

namespace Amasty\Knockout\Controller\Ajax;

use Magento\Checkout\Model\Sidebar;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Response\Http;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Json\Helper\Data;
use Psr\Log\LoggerInterface;
use Magento\Checkout\Model\Cart;

class CartUpdate extends Action
{
/**
* @var Sidebar
*/
protected $sidebar;

/**
* @var LoggerInterface
*/
protected $logger;

/**
* @var Data
*/
protected $jsonHelper;

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

/**
* @param Context $context
* @param Sidebar $sidebar
* @param LoggerInterface $logger
* @param Data $jsonHelper
* @codeCoverageIgnore
*/
public function __construct(
Context $context,
Cart $cart,
\Magento\Checkout\Model\Session $checkoutSession,
Sidebar $sidebar,
LoggerInterface $logger,
Data $jsonHelper
) {
$this->sidebar = $sidebar;
$this->logger = $logger;
$this->jsonHelper = $jsonHelper;
$this->_checkoutSession = $checkoutSession;
$this->cart = $cart;
parent::__construct($context);
}

/**
* @return $this
*/
public function execute()
{
$itemId = (int)$this->getRequest()->getParam('item_id');
$itemQty = (int)$this->getRequest()->getParam('item_qty');

try {
$this->updateQuoteItem($itemId, $itemQty);
return $this->jsonResponse();
} catch (LocalizedException $e) {
return $this->jsonResponse($e->getMessage());
} catch (\Exception $e) {
$this->logger->critical($e);
return $this->jsonResponse($e->getMessage());
}
}

/**
* Update quote item
*
* @param int $itemId
* @param int $itemQty
* @throws LocalizedException
* @return $this
*/
public function updateQuoteItem($itemId, $itemQty)
{
$itemData = [$itemId => ['qty' => $itemQty]];
$this->cart->updateItems($itemData)->save();
}

/**
* Get quote object associated with cart. By default it is current customer session quote
*
* @return \Magento\Quote\Model\Quote
*/
public function getQuote()
{
return $this->_checkoutSession->getQuote();
}


/**
* Compile JSON response
*
* @param string $error
* @return Http
*/
protected function jsonResponse($error = '')
{
return $this->getResponse()->representJson(
$this->jsonHelper->jsonEncode($this->sidebar->getResponseData($error))
);
}
}

And that’s it. We hope that our article helped you to understand how to update Magento 2 cart quantity by using AJAX.

According to the statistics, you may find helpfull the following question about jquery.

How can we help you?

Didn’t you find the answer to your question? We are always happy to help you out.

© 2009-2024 Amasty. All Rights Reserved.