Woocommerce - Product Page - How to create AJAX on "Add To Cart" button?

Tom Luz picture Tom Luz · Sep 17, 2014 · Viewed 77.3k times · Source

I want to make an "Add To Cart" button on a product page that would work with AJAX. How can I do it? When I add to cart on a product page - it refreshes the page, how can I make it work by AJAX?

The "Add to cart" button on "Quick View" on archive works by ajax - and it's great, but how can I do the same on product page?

I want to click on "Take me Home" on the product page which would then add the product with the selected attributes to my cart by ajax and will open that cart (like when you hover onto the bag image on menu) and shakes the bag image.

Answer

anatoliy_kot picture anatoliy_kot · Dec 10, 2014

We can use ajax from archive page. it's easy -

Remove old button which submiting form:

remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );

Add ajax-link from archive page to single product page:

add_action( 'woocommerce_single_product_summary', 'woocommerce_template_loop_add_to_cart', 30 );

P.S. JS Callback. For example you can show popup with links "Back to shop" and "Cart" or "Checkout"

$('body').on('added_to_cart',function(){
    // Callback -> product added
    //$('.popup').show();
});