Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery trigger for remove product from woocommerce cart ajax

Looking to run some jQuery when a product is removed from the cart in woocommerce. I thought this would do it, but it's not happening.

Any ideas?

jQuery( document.body ).on( 'updated_wc_div', function(){
//magic
});
like image 881
loveforfire33 Avatar asked Jan 26 '26 15:01

loveforfire33


2 Answers

There can be also triggered updated_cart_totals event when cart has updated. So, you can use the following workaround, as there is no one global event which triggered when the cart is updated:

jQuery( document.body ).on( 'updated_wc_div', do_magic );
jQuery( document.body ).on( 'updated_cart_totals', do_magic );

function do_magic() {
    // do magic
}
like image 141
Avag Sargsyan Avatar answered Jan 29 '26 12:01

Avag Sargsyan


You can remove the product from cart using this code :

main.js

 $.ajax({
    type: "POST",
    url: 'http://localhost/your_site/wp-admin/admin-ajax.php',
    data: {action : 'remove_item_from_cart','product_id' : '4'},
    success: function (res) {
        if (res) {
            alert('Removed Successfully');
        }
    }
});

functions.php

function remove_item_from_cart() {
$cart = WC()->instance()->cart;
$id = $_POST['product_id'];
$cart_id = $cart->generate_cart_id($id);
$cart_item_id = $cart->find_product_in_cart($cart_id);

if($cart_item_id){
   $cart->set_quantity($cart_item_id, 0);
   return true;
} 
return false;
}

add_action('wp_ajax_remove_item_from_cart', 'remove_item_from_cart');
add_action('wp_ajax_nopriv_remove_item_from_cart', 'remove_item_from_cart');
like image 35
Lathiya Fenil Avatar answered Jan 29 '26 11:01

Lathiya Fenil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!