“Add to cart” with Woocommerce and AJAX step by step

First of all … Why use AJAX?

  • This script that communicates the data to and from the server, improves the user experience by allowing changes to the pages without having to load them again. Imagine that each step you take in a web should refer to another page, and another, and another … The more steps and time your e-commerce load, the more you reduce the chances of selling. AJAX makes the actions take place immediately as if we were interacting with a PC program.
  • Use less bandwidth, which optimizes resources.
  • AJAX is supported by almost all web platforms, so it is highly compatible.

Let’s start!

1. Add Javascript

The first step is to include the javascript in your website, so add this code to your functions.php file.

 function bodycommerce_ajax_add_to_cart_script() {


wp_enqueue_script( 'bodycommerce-add-to-cart-ajax', get_stylesheet_directory() . '/js/add-to-cart-ajax.js', array('jquery'), '', true );

}
 
add_action( 'wp_enqueue_scripts', 'bodycommerce_ajax_add_to_cart_script',99 );

2. Create a file for Javascript

After adding the javascript, create a file in your child theme called “JS” and add a new javascript called “add-to-cart-ajax.js”.

3. Add jQuery to avoid recharging

Apply this code to prevent the button from sending the information to the database and reloading the page.

 jQuery( function( $ ) {

$( document ).on( 'click', '.single_add_to_cart_button', function(e) {
e.preventDefault();

});
});

4. Add the product to the cart

The jQuery will be used to collect the information from the website and add a product from the site to the cart.

You will need to know:

  • Product ID
  • Quantity
  • Variable ID
  • Variable item

The following example shows the code for a variable product since there are several hidden entries.

 would give the value for the Variation ID So to get all the information we need for a variable product we use: $variation_form = $( this ).closest( '.variations_form' ); var product_id = $variation_form.find( 'input[name=product_id]' ).val(); var quantity = $variation_form.find( 'input[name=quantity]' ).val(); var var_id = $variation_form.find( 'input[name=variation_id]' ).val();

With a variable item, it’s usually a bit more complicated. What we will do is add hidden inputs and use jQuery to fill the values of the product ID and quantity, which is what we need for a single product.

Create a new file in your child theme called Woocommerce and in that file, you must copy the file “content-single-product.php” that you will get from the Woocommerce plugin.

In that file, add the following html for the two hidden inputs. This will add the product ID as the value.

 <!--?php global $product;
$id = $product-&lt;get_id(); ?-->

<input id="product_id" type="hidden" value="&lt;?php echo $id ?&gt;" />
<input id="product_quantity" type="hidden" value="1" />

What if the customer wants to change the number of products?

Add the following code to update the quantity that the client wants and also match the hidden amount that we created.

 $ (". input-text.qty.text"). bind ('keyup mouseup', function () {
var value = $ (this) .val ();
$ ("# product_quantity"). val (value)
});

How do we send these hidden values to the database?

Locate this line of code that contains this information:

 var data = {
action: 'bodycommerce_ajax_add_to_cart_woo',
product_id: product_id,
quantity: quantity
variation_id: var_id,
variation: item
};

There you can see that the variables we created earlier have been added to the variable “data”. You should look at the action “bodycommerce_ajax_add_to_cart_woo ‘, which will call a PHP function.

You will see below that they are two separate functions that are called depending on whether it is a single or variable product, so we will have to add two functions later. First, you must add this javascript.

 jQuery( function( $ ) { $(".input-text.qty.text").bind('keyup mouseup', function () { var value = $(this).val(); $("#product_quantity").val(value) }); if ( typeof wc_add_to_cart_params === 'undefined' ) return false; $( document ).on( 'click', '.single_add_to_cart_button', function(e) { e.preventDefault(); $variation_form = $( this ).closest( '.variations_form' ); var var_id = $variation_form.find( 'input[name=variation_id]' ).val(); var product_id = $variation_form.find( 'input[name=product_id]' ).val(); var quantity = $variation_form.find( 'input[name=quantity]' ).val(); $( '.ajaxerrors' ).remove(); var item = {}, check = true; variations = $variation_form.find( 'select[name^=attribute]' ); if ( !variations.length) { variations = $variation_form.find( '[name^=attribute]:checked' ); } if ( !variations.length) { variations = $variation_form.find( 'input[name^=attribute]' ); } variations.each( function() { var $this = $( this ), attributeName = $this.attr( 'name' ), attributevalue = $this.val(), index, attributeTaxName; $this.removeClass( 'error' ); if ( attributevalue.length === 0 ) { index = attributeName.lastIndexOf( '_' ); attributeTaxName = attributeName.substring( index + 1 ); $this .addClass( 'required error' ) .before( ' Please select ' + attributeTaxName + ' ' ) check = false; } else { item[attributeName] = attributevalue; } } ); if ( !check ) { return false; } var $thisbutton = $( this ); if ( $thisbutton.is( '.single_add_to_cart_button' ) ) { $thisbutton.removeClass( 'added' ); $thisbutton.addClass( 'loading' ); if ($(".variations_form")[0]){ var product_id = $variation_form.find( 'input[name=product_id]' ).val(); var quantity = $variation_form.find( 'input[name=quantity]' ).val(); var data = { action: 'bodycommerce_ajax_add_to_cart_woo', product_id: product_id, quantity: quantity, variation_id: var_id, variation: item }; } else { var product_id = $("#product_id").val(); var quantity = $("#product_quantity").val(); var data = { action: 'bodycommerce_ajax_add_to_cart_woo_single', product_id: product_id, quantity: quantity }; } $( 'body' ).trigger( 'adding_to_cart', [ $thisbutton, data ] ); $.post( wc_add_to_cart_params.ajax_url, data, function( response ) { if ( ! response ) return; var this_page = window.location.toString(); this_page = this_page.replace( 'add-to-cart', 'added-to-cart' ); if ( response.error && response.product_url ) { window.location = response.product_url; return; } if ( wc_add_to_cart_params.cart_redirect_after_add === 'yes' ) { window.location = wc_add_to_cart_params.cart_url; return; } else { $thisbutton.removeClass( 'loading' ); var fragments = response.fragments; var cart_hash = response.cart_hash; if ( fragments ) { $.each( fragments, function( key ) { $( key ).addClass( 'updating' ); }); } $( '.shop_table.cart, .updating, .cart_totals' ).fadeTo( '400', '0.6' ).block({ message: null, overlayCSS: { opacity: 0.6 } }); $thisbutton.addClass( 'added' ); if ( fragments ) { $.each( fragments, function( key, value ) { $( key ).replaceWith( value ); }); } $( '.widget_shopping_cart, .updating' ).stop( true ).css( 'opacity', '1' ).unblock(); $( '.shop_table.cart' ).load( this_page + ' .shop_table.cart:eq(0) > *', function() { $( '.shop_table.cart' ).stop( true ).css( 'opacity', '1' ).unblock(); $( document.body ).trigger( 'cart_page_refreshed' ); }); $( '.cart_totals' ).load( this_page + ' .cart_totals:eq(0) > *', function() { $( '.cart_totals' ).stop( true ).css( 'opacity', '1' ).unblock(); }); } }); return false; } else { return true; } }); });

5. “Add to cart” with AJAX in PHP

Now we will go to the functions.php file and add the following code. The intention of this is to update the cart with the information received by the jQuery file.

 add_action ('wp_ajax_bodycommerce_ajax_add_to_cart_woo', 'bodycommerce_ajax_add_to_cart_woo_callback');
add_action ('wp_ajax_nopriv_bodycommerce_ajax_add_to_cart_woo', 'bodycommerce_ajax_add_to_cart_woo_callback');

function bodycommerce_ajax_add_to_cart_woo_callback () {
ob_start ();
$ product_id = apply_filters ('woocommerce_add_to_cart_product_id', absint ($ _POST ['product_id']));
$ quantity = empty ($ _POST ['quantity'])? 1: apply_filters ('woocommerce_stock_amount', $ _POST ['quantity']);
$ variation_id = $ _POST ['variation_id'];
$ variation = $ _POST ['variation'];
$ passed_validation = apply_filters ('woocommerce_add_to_cart_validation', true, $ product_id, $ quantity);
if ($ passed_validation && WC () -> cart-> add_to_cart ($ product_id, $ quantity, $ variation_id, $ variation)) {
do_action ('woocommerce_ajax_added_to_cart', $ product_id);
if (get_option ('woocommerce_cart_redirect_after_add') == 'yes') {
wc_add_to_cart_message ($ product_id);}
WC_AJAX :: get_refreshed_fragments ();}
else {
$ this-> json_headers ();
$ data = array (
'error' => true,
'product_url' => apply_filters ('woocommerce_cart_redirect_after_error', get_permalink ($ product_id), $ product_id));
echo json_encode ($ data);}
die ();}

add_action ('wp_ajax_bodycommerce_ajax_add_to_cart_woo_single', 'bodycommerce_ajax_add_to_cart_woo_single_callback');
add_action ('wp_ajax_nopriv_bodycommerce_ajax_add_to_cart_woo_single', 'bodycommerce_ajax_add_to_cart_woo_single_callback');

function bodycommerce_ajax_add_to_cart_woo_callback () {
ob_start ();
$ product_id = apply_filters ('woocommerce_add_to_cart_product_id', absint ($ _POST ['product_id']));
$ quantity = empty ($ _POST ['quantity'])? 1: apply_filters ('woocommerce_stock_amount', $ _POST ['quantity']);
$ passed_validation = apply_filters ('woocommerce_add_to_cart_validation', true, $ product_id, $ quantity);
if ($ passed_validation && WC () -> cart-> add_to_cart ($ product_id, $ quantity)) {
do_action ('woocommerce_ajax_added_to_cart', $ product_id);
if (get_option ('woocommerce_cart_redirect_after_add') == 'yes') {
wc_add_to_cart_message ($ product_id);}
WC_AJAX :: get_refreshed_fragments ();}
else {
$ this-> json_headers ();
$ data = array (
'error' => true,
'product_url' => apply_filters ('woocommerce_cart_redirect_after_error', get_permalink ($ product_id), $ product_id));
echo json_encode ($ data);}
die ();}

Ready!

If all the above was complicated, remember that Divi has a plugin called Divi BodyCommerce and allows this and many more functions related to the carts in e-commerce.