1
votes

I'm using Woocommerce and I'm trying to remove item from the mini cart using ajax.

By looking at woocommerce minicart.php file I have found the relevant functionality to removing item:

<?php
echo apply_filters( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    'woocommerce_cart_item_remove_link',
    sprintf(
        '<a href="%s" class="remove1" aria-label="%s" data-product_id="%s" data-cart_item_key="%s" data-product_sku="%s">&times;</a>',
        esc_url( wc_get_cart_remove_url( $cart_item_key ) ),
        esc_attr__( 'Remove this item', 'woocommerce' ),
        esc_attr( $product_id ),
        esc_attr( $cart_item_key ),
        esc_attr( $_product->get_sku() )
    ),
    $cart_item_key
);
?>

But I can't figure out how to run the command through ajax instead of refreshing the page. I have tried to modify code I found about adding to cart using ajax.

Didn't work, the page still refreshes.

Here is what I have tried:

$(document).on('click', '.remove1', function (e) {
e.preventDefault();
var $thisbutton = $(this),
        $form = $thisbutton.closest('form.cart'),
        id = $thisbutton.val(),
        product_qty = $form.find('input[name=quantity]').val() || 1,
        product_id = $form.find('input[name=product_id]').val() || id,
        variation_id = $form.find('input[name=variation_id]').val() || 0;

var data = {
    action: 'woocommerce_cart_item_removed',
    product_id: product_id,
    product_sku: '',
    quantity: product_qty,
    variation_id: variation_id,
};


$.ajax({
    type: 'post',
    url: wc_add_to_cart_params.ajax_url, // What params should I use?
    data: data,
    beforeSend: function (response) {
        $thisbutton.removeClass('added').addClass('loading');
    },
    complete: function (response) {
        $thisbutton.addClass('added').removeClass('loading');
    },
    success: function (response) {

        if (response.error && response.product_url) {
            window.location = response.product_url;
            return;
        }
    },
});
});

functions.php

add_action( 'woocommerce_remove_cart_item', 'update_cart', 10, 2 );

function update_cart(){
  //What to do here?
}

No debugging errors.

Few important things I haven't found information online for:

  • Which ajax url url: wc_add_to_cart_params.ajax_url should I use to remove item from mini cart?
  • How to handle the data transferred from the ajax to functions.php?

How can I remove item from Woocommerce mini cart using ajax?

1

1 Answers

0
votes

First of all, please check your WooCommerce settings to see if Ajax enables the add-to-cart button. If not, Enable it from the admin panel. Check out the screenshot click here to see the screenshot of admin panel setting for ajax

Then try to remove the product from the cart.