0

Every time a product is added to the basket by ajax and the mini cart is refreshed I need to be able to run some jQuery. I can't just simply create an even for add to cart because, I run some jQuery that checks if the mini cart has products inside it, but the add to cart even runs before the mini cart has added the products. This means that my if statement becomes false.

What can I do about this apart from creating a timeout in jQuery?

Here is the code I have modified from the current answers;

add_action( 'wp_footer', 'ajax_add_tocart_event' );

function ajax_add_tocart_event() {
    ?>
     <script type="text/javascript">
       jQuery( 'body' ).on( 'added_to_cart', function() {
            if( $('#mini_wrap .cart_list').length ){
                alert('hi');
            }
       } );
    </script>
    <?php
}
Reece
  • 2,581
  • 10
  • 42
  • 90
  • I have edited my question so it is now not a duplicate as my requirements are now different. – Reece Sep 17 '18 at 14:08

2 Answers2

2

You can do using following code.

   add_action( 'wp_footer', 'ajax_add_tocart_event' );
   function ajax_add_tocart_event() {
    ?>
     <script type="text/javascript">
       jQuery( 'body' ).on( 'added_to_cart', function( e, fragments, cart_hash, this_button ) {
              alert('product added to cart');
       } );
    </script>
    <?php
    } ?>
dipmala
  • 2,003
  • 1
  • 16
  • 17
  • Will I need the parameters passed in the jQuery function? All I will be doing is checking if my mini cart has products. Thanks – Reece Sep 17 '18 at 13:40
  • Yes you can do easily using ul length ul class is 'woocommerce-mini-cart' – dipmala Sep 17 '18 at 13:58
  • Thanks for your help but I require some other code. I have changed my question to reflect this. Still I will up vote you as this code does work for what I was asking for previously. – Reece Sep 17 '18 at 14:06
1

Put this code in functions.php file.

add_action( 'wp_footer', 'trigger_for_ajax_add_to_cart' );
function trigger_for_ajax_add_to_cart() {
    ?>
        <script type="text/javascript">
            (function($){
                $('body').on( 'added_to_cart', function(){
                    //do some code
                });
            })(jQuery);
        </script>
    <?php
} ?>
Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51