◦ Comprehensive security
◦ 24/7 support
Magento Guide → Cart → Empty
How to empty a Magento 2 cart using JS
Emptying a customer’s cart with a button click can improve usability and help support advanced shopping flows. If you’re building a custom frontend experience or integrating Magento with a JS-heavy theme, you’ll need to handle this without a full page reload.
Let’s walk through how to clear a Magento 2 cart using JavaScript and a custom controller.
Host Magento at full throttle.
Get secure, reliable Magento hosting so you can scale faster.
Why clear the cart with JavaScript?
JavaScript gives you more control over the customer experience when clearing the cart:
- You can trigger the action from a button, link, or custom UI element without a full reload.
- It’s useful in single-page apps, headless setups, or PWA frontends.
- You can clear the cart in response to timed events, abandoned cart logic, or custom workflows.
The key is to build a custom endpoint that safely empties the cart, then call it with JavaScript.
1. Create a custom controller to clear the cart
First, create a custom module with a controller that clears the current cart session. You’ll use the Magento\Checkout\Model\Cart class to truncate the quote and save it.
Here’s the full controller code:
<?php
namespace Vendor\Module\Controller\Cart;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Checkout\Model\Cart;
class Clear extends \Magento\Framework\App\Action\Action
{
protected $jsonFactory;
protected $cart;
public function __construct(
Context $context,
JsonFactory $jsonFactory,
Cart $cart
) {
$this->jsonFactory = $jsonFactory;
$this->cart = $cart;
parent::__construct($context);
}
public function execute()
{
$result = $this->jsonFactory->create();
try {
$this->cart->truncate()->saveQuote();
$result->setData(['success' => true, 'message' => __('Cart cleared successfully')]);
} catch (\Exception $e) {
$result->setData(['success' => false, 'message' => $e->getMessage()]);
}
return $result;
}
}Make sure to register your module and add the correct routes.xml entry to expose this controller at a URL like /vendor/module/cart/clear.
2. Add a JavaScript function to call the controller via AJAX
Once your controller is in place, you can call it from the frontend using JavaScript. Here’s an example using jQuery’s $.ajax:
function clearCart() {
$.ajax({
url: '/vendor/module/cart/clear', // Replace with your controller URL
type: 'POST',
dataType: 'json',
data: {
'form_key': window.FORM_KEY // Include form key for CSRF protection
},
success: function(response) {
if (response.success) {
console.log('Cart cleared successfully');
location.reload(); // Or reload just the cart UI
} else {
console.error('Error clearing cart:', response.message);
}
},
error: function(error) {
console.error('Error during AJAX call:', error);
}
});
}
Make sure window.FORM_KEY is available on the page. It’s a required CSRF token for any POST request in Magento.
3. Trigger the function with a button or event
To use the function, hook it into a button click or another user event:
<button onclick="clearCart()">Clear Cart</button>You can place this in a PHTML template or insert it into the DOM dynamically. If you’re building with RequireJS, you may also need to declare jQuery as a dependency in your module’s requirejs-config.js.
In a Knockout-based UI (like the mini-cart), you could also bind this to an observable or UI component.
4. Refresh cart and mini-cart UI after clearing
Clearing the cart won’t automatically update the mini-cart or cart sidebar. After calling the AJAX controller, you should refresh the UI so the customer sees the cart as empty.
The fastest way is to reload the page:
location.reload();For a smoother experience, especially in headless or PWA setups, reload just the cart data:
require(['Magento_Customer/js/customer-data'], function(customerData) {
customerData.reload(['cart'], true);
});This updates Magento’s customer data sections, including the mini-cart, without a full reload.
5. Key security and performance considerations
Don’t skip these technical best practices:
- CSRF protection: Always include form_key in your request data.
- Controller access: Restrict the controller to logged-in users if appropriate using $this->_auth->isLoggedIn() or a plugin.
- Caching: If you’re using Varnish or other page caches, make sure they aren’t serving stale cart blocks.
- Mini-cart update: Use customerData.reload() if your theme uses Magento’s Knockout-based mini-cart.
6. Troubleshooting tips
If something’s not working, check the following:
- Is your controller URL correct? Test it with a POST tool like Postman.
- Does your module declare the controller route in routes.xml?
- Are browser console errors showing a CORS issue or missing form key?
- Is the JavaScript loaded on the page? Add a console.log() at the top of your script to check.
- Are Magento logs (var/log/exception.log) showing any backend errors?
7. When to use this method (and when not to)
This approach is flexible but not ideal for every situation.
Use it when:
- You want to offer a “Clear Cart” button on the frontend
- You’re working with a custom JavaScript or headless theme
- You’re building a tool for customer service reps or admins to manage carts quickly
Avoid it when:
- You need complex cart validation before clearing
- You’re clearing multiple user carts from the admin area (use backend services or CLI)
- You require logging or audit trails for cart actions
Next steps for emptying a Magento 2 cart with JS
Using JavaScript and a custom controller gives you a fast, flexible way to clear Magento 2 carts. It’s perfect for user-friendly features, testing tools, and custom shopping flows.
To get started, set up your custom controller, wire up the frontend AJAX call, and test it thoroughly in your theme.
Ready to upgrade your Magento experience? Professional hosting improves speeds, security, and reliability for a website and a brand that people find engaging and trustworthy.
Liquid Web offers the raw infrastructure power you need with mission-critical features that keep your store running smoothly. Most importantly, our in-house Magento experts are standing by to help with both hosting and Magento application roadblocks.
Click through below to explore all of our Magento hosting options, or chat with an expert right now to get answers and advice.
Ready to get started?
Get the fastest, most secure Magento hosting on the market
Additional resources
What is Magento Ecommerce? →
A complete beginner’s guide to the Magento Ecommerce platform
Magento shopping cart: How to setup, optimize, and manage →
Let’s walk through everything you need to know about configuring, optimizing, and maintaining your Magento cart the right way.
Best Magento ERP extensions →
Our top 10 compared so you can decide which is best for your business