Habib
Habib

Reputation: 308

jQuery script not working in woocommerce_cart_item_removed hook

I am trying to run a javascript function after product is removed from the cart, but not working... I am using the function below

function action_woocommerce_remove_cart_item( $cart_item_key, $instance ) {
    ?>
    <script>
    $(document).ready(function(e) {
        alert('removed');
        $('#cart_ifram').attr('src','<?php echo home_url(); ?>/cart/');
    });
    </script>
    <?php
};
add_action( 'woocommerce_cart_item_removed', 'action_woocommerce_remove_cart_item', 10, 2 ); 

I have also tried woocommerce_cart_item_removed hook but it didn't worked for me. Also woocommerce updated cart hook works when an item is added to cart but not in my case... Thanks for help...

Upvotes: 2

Views: 1634

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253988

1) To get jQuery working with Wordpress you need to use jQuery instead of shortland $ at the begining, this way:

jQuery(document).ready(function($){
    alert('removed');
    $('#cart_ifram').attr('src','<?php echo home_url(); ?>/cart/');
});

… or …

(function($){
    alert('removed');
    $('#cart_ifram').attr('src','<?php echo home_url(); ?>/cart/');
})(jQuery);

2) You are using the correct hook, but Javascript/jQuery don't seem to work in it. Try this code and you will see that you get a custom notice when removing a cart item:

add_action( 'woocommerce_cart_item_removed', 'action_woocommerce_remove_cart_item', 10, 2 );
function action_woocommerce_remove_cart_item( $cart_item_key, $instance ) {

    // Displaying a custom notice
    wc_add_notice( 'ITEM REMOVED', 'error' );

    ?>
    <script>
        jQuery(document).ready(function($) {
            alert('Item removed');
            console.log('Item removed');
        });
    </script>
    <?php
}

On cart page, there is a lot of WooCommerce javascript events that are certainly killing your custom made jQuery process, so is going to be complicated to get it work.

Upvotes: 1

Related Questions