Search
×
Log in or create an account
If you have an account with us, please log in.

You have no items in your shopping cart.

Frequently Asked Questions

How can we help you?

banner image

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.

In this article, we’ll consider how to use AJAX to update Magento 2 mini cart quantity.

Let’s start.

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

You need to create a controller for the customer data section. It will update the mini cart quantity 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.

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 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.

Rate the answer?

Total rating: 5.0

If you didn’t find the answer on your question, please, ask here:

Back to top