Ajax add to cart issue in Woocommerce 2.5.2

I’m using Woocommerce and I’ve customized my site to display the product titles in a table and when clicked the product is placed via ajax in the Woocommerce mini-cart widget without a page refresh.

When I update to ‘Woocommerce 2.5.2’ the Ajax add to cart no longer works and the page refreshes.

Read More

The current link I use to add a product is:

$html = $html . '<div class="numlist_thumb"><a data-product_id="' . $id1 . '" data-product_sku="' . $number1 . '" class="numbertabanchor add_to_cart_button dp-button product_type_simple" rel="nofollow" href="/?add-to-cart=' . $id1 . '">' . $number1 . '</a></div>';

I would really appreciate any suggestions as to how to add a product via ajax without a page refresh.

Related posts

3 comments

  1. This is the theme conflicts with woocommerce. I faced this problem too. So whenever the woocommerce launched any major update, theme also updated according to latest woocommerce. So you have to update your theme according to woocommerce.

  2. Add the “ajax_add_to_cart” class to your <a> tag

    As a reference have a look at my code for single-product/add-to-cart/simple.php

    <button type="submit" class="single_add_to_cart_button add_to_cart_button button ajax_add_to_cart button--itzel button--text-thick" data-quantity="1" data-product_id="<?php echo $product->id; ?>"><i class="button__icon icon icon-cart"></i><span><?php echo esc_html( $product->single_add_to_cart_text() ); ?></span></button>
    
  3. You can easily create the add to cart functionality via the [wp_ajax][1] action, and in the callback function you can simply add the following code

    add_action( "wp_ajax_custom_add_to_cart", "custom_add_to_cart_callback" );
    add_action( "wp_ajax_nopriv_custom_add_to_cart", "custom_add_to_cart_callback" );
    function custom_add_to_cart_callback(){
         global $woocommerce;
         $woocommerce->cart->add_to_cart( $_POST[ 'prod_id' ] );
         wp_die();
    }
    

    After this you can easily just make an ajax call to the server, where you will post the product id as variable prod_id and add another variable named action with value custom_add_to_cart

Comments are closed.