WooCommerce

AJAX Add to Cart on the Single Product Page

AJAX Add to Cart on the Single Product Page

The next post on improving your store that is being built using WooCommerce will be ajax add to cart button on the single product page.

A few weeks ago, one of my customers wrote me a help request in the support for my theme. He wanted to add on the product page, the ability to add products to the cart using AJAX. It was a good idea for new WooCommerce tutorial post.

First we need to add a click event to the add to cart button in the WooCommerce product page

$('.entry-summary form.cart').on('submit', function (e)
{
    e.preventDefault();

    $('.entry-summary').block({
        message: null,
        overlayCSS: {
            cursor: 'none'
        }
    });

    var product_url = window.location,
        form = $(this);

    $.post(product_url, form.serialize() + '&_wp_http_referer=' + product_url, function (result)
    {
        var cart_dropdown = $('.widget_shopping_cart', result)

        // update dropdown cart
        $('.widget_shopping_cart').replaceWith(cart_dropdown);

        // update fragments
        $.ajax($warp_fragment_refresh);

        $('.entry-summary').unblock();

    });
});

To avoid an errors with refreshing the card fragment, will be better to create a new function for this.


// Ajax add to cart on the product page
var $warp_fragment_refresh = {
    url: wc_cart_fragments_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'get_refreshed_fragments' ),
    type: 'POST',
    success: function( data ) {
        if ( data && data.fragments ) {

            $.each( data.fragments, function( key, value ) {
                $( key ).replaceWith( value );
            });

            $( document.body ).trigger( 'wc_fragments_refreshed' );
        }
    }
};

It should be something like this:


// Ajax add to cart on the product page
var $warp_fragment_refresh = {
    url: wc_cart_fragments_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'get_refreshed_fragments' ),
    type: 'POST',
    success: function( data ) {
        if ( data && data.fragments ) {

            $.each( data.fragments, function( key, value ) {
                $( key ).replaceWith( value );
            });

            $( document.body ).trigger( 'wc_fragments_refreshed' );
        }
    }
};

$('.entry-summary form.cart').on('submit', function (e)
{
    e.preventDefault();

    $('.entry-summary').block({
        message: null,
        overlayCSS: {
            cursor: 'none'
        }
    });

    var product_url = window.location,
        form = $(this);

    $.post(product_url, form.serialize() + '&_wp_http_referer=' + product_url, function (result)
    {
        var cart_dropdown = $('.widget_shopping_cart', result)

        // update dropdown cart
        $('.widget_shopping_cart').replaceWith(cart_dropdown);

        // update fragments
        $.ajax($warp_fragment_refresh);

        $('.entry-summary').unblock();

    });
});

Next, we need to change the template of the add to cart button for simple products

Please copy the template file ( plugins/woocommerce/templates/single-product/add-to-cart/simple.php ) into your theme ( themes/your theme name/woocommerce/single-product/add-to-cart/simple.php ) and replace the line:


<button type="submit" name="add-to-cart" value="<?php echo esc_attr( $product->get_id() ); ?>" class="single_add_to_cart_button button alt"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></button>

with this line:


<input type="hidden" name="add-to-cart" value="<?php echo esc_attr( $product->get_id() ); ?>" />

<button type="submit" class="single_add_to_cart_button button alt"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></button>
For grouped and variable products, we don’t need to do it

Do you want to see how it works?

Demo

Comments (4)

  • Avatar

    Anil

    |

    Hi,

    Woocommerce single product page add to cart button code is good and ajax proper call in my localsite but one issue in ajax function. Successfully Product added to cart and then after woocommerce mesage not display. Please immediately solved my issue.

    Thanks

    Reply

    • Avatar

      Alex Podolyan

      |

      Hello,

      Just replace this code snippet

      
      $('.entry-summary form.cart').on('submit', function (e)
      {
          e.preventDefault();
      
          $('.entry-summary').block({
              message: null,
              overlayCSS: {
                  cursor: 'none'
              }
          });
      
          var product_url = window.location,
              form = $(this);
      
          $.post(product_url, form.serialize() + '&_wp_http_referer=' + product_url, function (result)
          {
              var cart_dropdown = $('.widget_shopping_cart', result),
                  woocommerce_message = $('.woocommerce-message', result);
      
              // update dropdown cart
              $('.widget_shopping_cart').replaceWith(cart_dropdown);
      
              // Show message
              $('.type-product').eq(0).before(woocommerce_message);
      
              // update fragments
              $.ajax($warp_fragment_refresh);
      
              $('.entry-summary').unblock();
      
          });
      });
      

      Reply

      • Avatar

        Anil

        |

        Hi alexnet,
        Thank you very much for your help. The code you gave worked perfectly as I wanted.
        Thanks again…

        Reply

  • Avatar

    dinesh

    |

    great article and code working fine .. 🙂

    Reply

Leave a comment

Subscribe to our Newsletter