WooCommerce

WooCommerce – 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. So let’s do it together 🙂

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();

    });
});

I had some difficulties with refreshing the card fragment, so I created my own 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 (8)

  • 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

      alexnet

      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

    ali

    Hi
    Thank you very much brother for this explanation
    But unfortunately I did not know where to put this code
    I mean, you did not specify in which page php put this code
    Second order Is it possible to work this code within the space I am to download and activate it on my site

    Third thing I suffer from this is that I am an online store site but I do not know how to add products with AJAX This is myfoodsneed.com site

    Please, my brother, do not be late to reply and please do a video to explain or to work with these codes or explain in a way that I can understand you thank you broth

    Reply

    • Avatar

      alexnet

      Hello,

      If you use DIVI, try to insert the code in the special field on the Divi Theme Options page.

      Reply

    • Avatar

      alexnet

      And you can enable AJAX add to cart buttons on product archive pages.

      Reply

  • Avatar

    Chris

    Great code thanks… can you use this approach if you already disabled cart fragments?

    https://wordpress.org/plugins/disable-cart-fragments-littlebizzy/

    Or the plugin will cancel your feature?

    Reply

    • Avatar

      alexnet

      Hello,

      
      url: wc_cart_fragments_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'get_refreshed_fragments' ),
      

      As you can see, my code uses the variable wc_cart_fragments_params, and if you use this plugin you will get a JS error. But this can easily be fixed, for example, like this

      
      var $warp_fragment_refresh = {
          url: window.location.pathname+'?wc-ajax=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' );
              }
          }
      };
      

      Reply

Leave a comment