AJAX remove item from minicart

I’m trying to add a remove button/link to the minicart so items can easily be removed from there as well. I’m mostly copying the ajax code from the the theme-red and I’m thinking, I would need a form generated with each item in the cart, containing the following:

<form class="rmvForm" action="CommerceConfig.cart_url" method="POST">
  <input type="hidden" name="update_cart" value="1">
  <button name="remove_item" value="item.product">remove</button>
</form>

Now, I’m not sure how to handle the script part. Do I need to create a separate removeFromCart-function or can this be handled by the updateMiniCart (or another existing) function?

I’ve tried something like this, but it’s not working:

rmvForm.addEventListener('submit', function(e) {
  e.preventDefault();
  rmvForm.classList.add('commerce-loader');
  _request('POST', CommerceConfig.cart_url, new FormData(rmvForm), updateMiniCart);
});

I’m probably doing something obvious wrong, so would love to be enlightened.

Here’s what the normal form looks like in the cart:

<button 
    class="c-cart-item-remove-button c-button" 
    aria-label="{{ lex('commerce.cart.remove_product') }}" 
    name="remove_item" 
    value="{{ item.id }}"
>&times;</button>

So basically you need to submit remove_item=item.id

Mark helped me tweak this one, basically the script parts needs to be adjusted a bit:

function _updateMiniCartResponse(response) {

  // ...

  response.order.items.forEach(function (item) {

    // generate remove form with button name="remove_item" and value="{{ item.id }}"

    if (rmvForm) {
      rmvForm.addEventListener('submit', function(e) {
        e.preventDefault();
        rmvForm.classList.add('commerce-loader'); 

        const formData = new FormData();
        formData.append("remove_item", rmvFormBtn.value);              
        _request('POST', CommerceConfig.cart_url, formData, _updateMiniCartResponse);
      });
    }
  }
}

Works like a charm now!

And to add to that, you need Commerce 1.2.8 or 1.3.0-dev5 which makes item.id available as that was previously not included. :wink:

1 Like