SKS
SKS

Reputation: 68

Call a function from enqued js file on wordpress

I have enqueued the JS file to my WordPress plugin using :PHP

   public function enqueue_scripts() {
            wp_enqueue_script('my_awesome_plugin', plugins_url(  '../assets/main.js', __FILE__), NULL, NULL, true );
    }
   add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );

I have a function called addedToCart() on that file : JS

addedToCart(){
  console.log("Added to Cart");
}

I need to call that function once a user added to his cart. I can use this hook : PHP

add_action( 'woocommerce_add_to_cart', array( $this, 'add_to_cart' ), 10, 6 );

public function add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data)
    {
?> 
<script>
    //What code should I add <-- Line
<script>
<?PHP
}

What code should I write to call that function on the JS File?

Thanks for your time.

Upvotes: 0

Views: 64

Answers (1)

Vinay Jain
Vinay Jain

Reputation: 882

You can listen to Woocommerce Js events to achieve this:

jQuery(document).ready(function($){
    $('body').on( 'added_to_cart', function(){
        //alert("Added to cart");
        addedToCart(); //your function
    });
});

Here's the list of events available around add-to-cart scenarios:

$( document.body ).trigger( 'adding_to_cart', [ $thisbutton, data ] );
$( document.body ).trigger( 'added_to_cart', [ response.fragments, response.cart_hash, $thisbutton ] );
$( document.body ).trigger( 'removed_from_cart', [ response.fragments, response.cart_hash, $thisbutton ] );
$( document.body ).trigger( 'wc_cart_button_updated', [ $button ] );
$( document.body ).trigger( 'cart_page_refreshed' );
$( document.body ).trigger( 'cart_totals_refreshed' );
$( document.body ).trigger( 'wc_fragments_loaded' );

Upvotes: 1

Related Questions