Create A Customizable AJAX Add To Cart Button In Bricks Builder

Create A Customizable AJAX Add To Cart Button In Bricks Builder

In Bricks, you can simply create an Add To Cart button from a dynamic data / function {woo_add_to_cart}. This button supports AJAX as well if you activate the Enable AJAX add to cart buttons on archives in WooCommerce > Settings > Products > Add to cart behaviour.

Activate AJAX add to cart in WooCommerce settings page

Since we are using a visual page builder, why don’t we create this in the builder and so we can style and customize it like a boss?

In this tutorial, I will place my AJAX add to cart button in my custom product loop template. Please feel free to read the product loop tutorial if you want to build yours too.

My Own AJAX add to cart button

Step 1: Bricks Button Element

Important Note

If you are following my product loop tutorial, remember to remove the Outer wrapper link. It might break your layout if link wraps in another link / button wraps in another button

Just add a Button element in the product loop template.

New button at the bottom of my loop

In CONTENT tab, put in your text and icon. For the LINK settings, Link type set to External URL, URL cannot be blank. At least a # to make the button clickable. Best is follow mine so it will populate a dynamic add-to-cart URL. (This doesn’t affects the AJAX function)

URL cannot be empty! At least a # or follow my setting.

Step 2: Transform Normal Button To AJAX Add To Cart

At this stage, your button just behave like a normal one, either clicking it brings you to top of the page because your are using anchor URL (#). If you use ?add-to-cart=post_id in the button URL, this will successfully add the product to cart but it’s not AJAX way.

It’s quite easy to transform the native button to WooCommerce AJAX add to cart. Just need to add some CSS classes and custom attributes will do!

Heads to STYLE tab of the button, set CSS classes as add_to_cart_button ajax_add_to_cart

Remember to separate the classes by space.

Add Attributes:

  • data-quantity : Should set as 1, so the button will add 1 quantity of the current product to cart. To control this value dynamically, you can use JavaScript solution but I am not going to cover in this tutorial.
  • data-product_id: The product id when making AJAX add to cart. Use dynamic post_id to dynamically set it. Of course gonna be in a loop, otherwise the post_id always the same. Check my tutorial for WooCommerce Product Loop Template if you don’t know what I am talking about.
  • aria-label: This is for accessibility.
data-quantity
data-product_id
aria-label

Now, let us save and test in Frontend!

AJAX works! Need improvement.

It works, but we got 2 issues to fix.

  • No indication when AJAX processing and completed.
  • For variable products, it might added successfully but the added product doesn’t has selected option.

Step 3: AJAX Indication

We can use jQuery to hook on WooCommerce events (WooCommerce is still using jQuery). When making call, I will change the “Add Cart” text to “Adding”. When AJAX completed, change it to “Added”.

2022 Aug 17 Update: You can use the same event to redirect visitor to checkout page. Just act like a Buy Now button.

Since this jQuery might be executing in anywhere, I will place my code in Bricks > Settings > Custom Code > Body (footer) scripts

Bricks > Settings > Custom Code > Body (footer) scripts

Important Note

Please don’t use Code element if you are inside a loop unless it’s a special requirement and you know what you are doing. Imagine how many duplicated codes will be rendering in frontend.

<script>
(($)=>{
	$(document).ready(()=>{

		// When Adding To Cart
		$('body').on('adding_to_cart', (e, button, data)=>{
			// Change my Text to "Adding". I use lastChild because firstChild is my Icon
			button[0].lastChild.textContent = "Adding..."
		});
		
		// When Added To Cart
		$('body').on('added_to_cart', (e, fragments, cart_hash, button)=>{
			// Change my Text to "Added"
			button[0].lastChild.textContent = "Added"
		});
	})
})(jQuery)
</script>

Buy Now Button JavaScript Example

// Example to redirect visitor to checkout page after add to cart
// Just change your button text to Buy Now if necessary
$('body').on('added_to_cart', (e, fragments, cart_hash, button)=>{
	// You can use setTimeout to delay redirection if necessary
	setTimeout( function() {
		window.location.href = `${window.location.origin}/checkout`
	}, 800 )
});

To style our button, we can make use loading and added CSS classes which will be injected by WooCommerce while making AJAX call. These 2 classes will be added on the button element.

Below CSS code added on my custom button.

root.loading i {
  -webkit-animation: spin 1s linear infinite;
  animation: spin 1s linear infinite;
}

root.loading i::before {
  content: "\e619";

}

root.added i::before {
  content: "\e64d"
}

Note that I change the icon content to \e619 and \e64d because I am using Themify icons. You can replace them as you like. This CSS part can be adjusted as you like. The spin animation comes from Bricks frontend.min.css

AJAX button CSS

At this stage, your button should looks like this.

Better user experience right?

Step 4: Dynamically Display Button

To avoid errors while adding variable product to cart via AJAX, the best way is display another normal button to direct visitor to the variable product’s page.

Create another simple button below the AJAX add to cart button.

New button
Normal button just set the link to product post_url
2 buttons in the product loop now

Write a simple function in your functions.php or via WPCodebox plugin. This will return True or False dynamically.

<?php

function itchy_is_simple_product() {
	global $product;
	return is_a( $product, 'WC_Product_Simple' );
}


?>

And you can choose either 1 method below to use this function.

Method A: Conditional Visibility Plugin (Unofficial)

I wrote a free conditional display plugin for Bricks in June 2022. You can use it to show or hide the button in Builder mode. Very handy if you are using dynamic data directly like MetaBox or ACF custom fields as the condition comparison values.

Configure the condition in ITCHY ADVANCED tab:

Conditional settings on AJAX button

Conditional settings for normal button

Method B: bricks/element/render Filter

If you prefer coding way, then copy below code into functions.php or via WPCodeBox. Remember to change the element IDs to yours.

Find your element ID
<?php

add_filter( 'bricks/element/render', 'itchycode_conditional_display_buttons', 10, 2 );

function itchycode_conditional_display_buttons( $show, $element ) {
	// Replace your button IDs here
	if( $element->id !== 'qlnmvz' &&  $element->id !== 'rsipdc') return $show;
	
	return itchy_is_simple_product();
}

Check in Frontend, it’s perfect now!

Perfect!

Get access to all 537 Bricks code tutorials with BricksLabs Pro

6 comments

  • kirkfall

    Hello, do you have any plans on making a pro tutorial for this?

    "data-quantity : Should set as 1, so the button will add 1 quantity of the current product to cart. To control this value dynamically, you can use JavaScript solution but I am not going to cover in this tutorial."

    I want to enable the same style of add to cart button on my single product page.

  • kirkfall

    Hello, I was following this guide and the product loop guide as a trial before purchasing the pro version.

    "If you are following my product loop tutorial, remember to remove the Outer wrapper link. It might break your layout if link wraps in another link / button wraps in another button"

    Where do I select this option?

    Another issue: in the bricks builder it displays the proper add to cart radio button that was added from the tutorial. However, on the live site, it displays both the add to cart button and the default woocommerce add to cart button.

  • Hi, Jenn. Thanks for the information.
    How can I now use this knowledge to add the ability to add a product option to the cart using ajax? For example, to display a radio button here with a selection of options and the option to order immediately

  • gustavo

    thanks for your post. It's a great help.

    I don't know if you could help me, in my case I want to make an AJAX add to letter for variable product where I want to put the id and its specific variation. Can this be done?

    Thank you very much in advance

  • Hi Jenn,
    I am using Bricks add-to-cart element which I Ajaxified with the css and data attributes you also mention in your tutorial.
    I would be interested in knowing how to control data-quantity value dynamically with JavaScript. Thanks, Max

    • Hi Max,

      Basically, you need to listen to 2 different events.
      1. Click event on the plus / minus span
      2. Input event on the quantity input
      3. Create a function to set your button data-quantity attribute value to the quantity input value.


      // Example
      const setAjaxQty = (e) => {

      // some logic to get currentAjaxBtn and currentQtyInput
      currentAjaxBtn.setAttribute('data-quantity', currentQtyInput.value )

      }
      document.querySelector('form.cart .quantity input.qty').addEventListener('input', setAjaxQty )
      document.querySelector('form.cart .quantity .action.plus, .quantity .action.minus').addEventListener('click', setAjaxQty )

      I am not able to give you the example of full code, because I am not sure how your button structure and the classes like.

Leave your comment

 

Related Tutorials..

Pro
Query Variables Condition in Bricks

Query Variables Condition in Bricks

This Pro tutorial provides the steps to register a custom function that returns true or false depending on whether the current page URL has specific…
Appending WooCommerce Endpoint Names To My account Page Titles in Bricks

Appending WooCommerce Endpoint Names To My account Page Titles in Bricks

Adding the WooCommerce endpoint names, “Orders”, “Downloads” after the WooCommerce ‘My account’ Page’s title text at the various endpoint URLs.
Categories:
Conditionally Outputting Based on Query Count in Bricks

Conditionally Outputting Based on Query Count in Bricks

Update on 22 Sep 2023: There's a much simpler built-in method now. See this post. In the Bricks Facebook group a user asks: Is there…
Categories:
Pro
Checking if the current Page/Post has Children i.e. is a Parent in Bricks

Checking if the current Page/Post has Children i.e. is a Parent in Bricks

Shows how we can check whether the current Page or Post (of any hierarchical post type) is a parent
Categories:
Pro
Conditional Related Posts in Bricks

Conditional Related Posts in Bricks

How to output a section only if there is at least 1 related post for the current post being viewed.
Categories:
How to add a “Sold Out” badge for out of stock products in Bricks

How to add a “Sold Out” badge for out of stock products in Bricks

Looking to add a "Sold Out" badge for products in the Shop page for WooCommerce products that are out of stock when using Bricks' Products…