There are two ways of emptying the shopping carts in a theme: a form or an asynchronous JavaScript call.

Introduction

In each of the examples below, a form is created on the page to empty the shopping cart:

<form id="cartEmptyForm" action="/cart/empty" method="POST">
    <button>{%ClearCart}</button>
</form>

You can add the form to any page where the shopping cart or its parts are displayed. A good practice is to display a shopping cart preview on every page (e.g. with the {MiniCart} tag) and provide a detailed preview on the shopping cart page.

The JavaScript examples of this articles use jQuery functions. If you use the scripts described in this article in your own theme, make sure that jQuery has been added to the page.

To add jQuery to a page, use the {SupportScripts} tag.

Emptying the shopping cart with a form

When you add the attribute action="/cart/empty" to the form, the shopping cart is emptied when the form is submitted. The form does not need to have any other fields than the submit button, that is, the <button type="submit"> element.

Emptying the shopping cart with JavaScript

If you'd like to reduce the number of page reloads in your online store, you can implement an AJAX call for emptying the shopping cart.

In the code below, the shopping cart is emptied and the element that contains the {MiniCart} tag is reloaded:

function emptyAndReloadCart() {
    $.ajax({
        type: "POST",
        url: "/cart/empty",
        data: "", // the data attribute can be left blank or removed altogether
        success: function() {
            /* Now the shopping cart is empty
            *
            * The element that contains the MiniCart tag is emptied
            */
            $("#MiniCartContainer").empty();

            // MiniCart is retrieved asynchronously and written back to its original location
            $.get('/interface/MiniCart', function (response) {
                $("#MiniCartContainer").html(response);
            });
        }
    });

// The function that empties the shopping cart is placed in the submit button
$.on("click", "#cartEmptyForm>button", function(event) {
    event.preventDefault();
    emptyAndReloadCart();
});

If the form for emptying the shopping cart is used on the shopping cart page, you may want to reload the contents of the shopping cart asynchronously so that the customer can see the change without page reload.

You can implement multiple functions connected to purchasing by using asynchronous JavaScript calls. Read also the following articles about asynchronous actions: