What is AJAX?

Ajax is a client-side script that communicates to and from a server/database without the need for the page to reload.

Below is a gif of what ajax add to cart does.

add-to-cart Woocommerce

Enqueuing the Javascript

The first step is to add a javascript script to your site, to do this add the following to your functions.php

1
2
3
4
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 );

After this create a new folder in your child theme called “js” and in that add a new javascript script called “add-to-cart-ajax.js”.

Javascript side of the AJAX add to cart

The main asset to ajax is that you dont need to reload the page to send data to the database, so the first step in the js creation is to prevent the page to reload.

1
2
3
4
5
6
7
jQuery( function( $ ) {
 
$( document ).on( 'click', '.single_add_to_cart_button', function(e) {
e.preventDefault();
 
});
});

The above code prevents the button to send the information to the database and reload the page.

So now I have disabled the ability to send information to the database, how do we add a product to the cart? Well, we use jQuery to gather information from the site.

The information we need are as follows:
Product ID
Quantity
Variation ID (if variable product)
Variation Item (if variable product)

So how do we get this? Well with a variable product it is quite straightforward as there are hidden inputs with all this information for example

Source: https://diviengine.com/woocommerce-add-cart-ajax-single-variable-products-improve-ux/