Posted on 3 Comments

The Ultimate Guide To Adding Products To Cart Using Ajax In WooCommerce

The Ultimate Guide To Adding Products To Cart Using Ajax In WooCommerce 1

Working with WooCommerce brings me a lot of joy. If you are a developer, I hope the experience I’m sharing below will be helpful to you.

How to add a simple product to cart using ajax

Adding a simple product via ajax is very simple. From any page, you send the following request, via POST or GET:

{
add-to-cart: product_id,
quantity: x
}

So, for example, I have my product here which has ID 30:

woocommerce-simple-product

Now, if I want to add this product to cart, I simply append the following data to any URL of my website:

?add-to-cart=30&quantity=2

In this example, I’m going to add two products to cart.

For example, I append the string above to the cart url, which makes the full URL like so:

http://localhost/wordpress/cart/?add-to-cart=30&quantity=2

If I open that URL in my browser, I will be redirected to cart page and the product will be in cart.

The Ultimate Guide To Adding Products To Cart Using Ajax In WooCommerce 2

Cool, isn’t it 🙂

Now, simple product is simple. How about variable products? I requires a bit more work.

 

How to add a variable product to cart using ajax

With variable product, you need to find the variation ID to add the exact product you need to cart. If you use the parent product ID, you may see an error, which is not surprised at all. Let me show you.

I have this product:

woocommerce variable product

As you can tell from the product page, it’s a variable product (select boxes to select the variations, price in range).

Now, the product id is 31. If I execute the following URL:

http://localhost/wordpress/cart/?add-to-cart=31&quantity=2

You’ll see this error:

The Ultimate Guide To Adding Products To Cart Using Ajax In WooCommerce 3

It is not hard to understand, right? Since the product is a variable product, you will need to find the variation ID.

Where to find the variation ID? Let’s do an inspection, shall we?

If you right click on one of the select boxes (to select variation) and click on inspect (on Chrome), you’ll see this:

The Ultimate Guide To Adding Products To Cart Using Ajax In WooCommerce 4

As you can see, our select box is inside a form. That form has an attribute called data-product_variations . This attribute contains the JSON data of all variations of our product. Let’s extract the data using jQuery.

extract variable product data in woocommerce

as you can see that, I select the form with the selector .variations_form.cartif you know jQuery or CSS selector, this part shouldn’t be strange to you.

I was able to extract the JSON string from the attribute data-product_variations and turned that into javascript object using JSON.parse.

Now, you can see that the data is an array contains 4 elements. Since my product has two attributes “Color” and “Size”, it’s not surprising that there are 4 variations.

Let’s expand one of the 4 variations and see what we have:

The Ultimate Guide To Adding Products To Cart Using Ajax In WooCommerce 5

There are a tons of data and surely you’ll see the variation_id is 150.

That’s all we need to add this product to cart.

Now, let’s navigate to this URL:

http://localhost/wordpress/cart/?add-to-cart=150&quantity=2

Sure enough, the product is added to cart.

successfully add variable product to cart using custom URL

Interesting, right?

Now, you are able to add simple and variation products to cart, which is great. However, if you notice the cart at the navigation bar. It’s not updating if you send the requests via ajax. How can you fix that?

How to add products to cart and update the cart widget(at the navigation bar)

To add the products to cart and then update the cart widget, you’ll need a different approach. At least, you need a different URL to send the request to.

Are you ready?

You still can send the request to any URL of your site, however, this time, you need a new parameter:

?wc-ajax=add_to_cart

Let’s open the browser’s console and enter the following data:

jQuery.post('http://localhost/wordpress/cart/?wc-ajax=add_to_cart', {product_id: 150, quantity: 10}, function(response){ console.log(response); })

The Ultimate Guide To Adding Products To Cart Using Ajax In WooCommerce 6

We are going to print out the response from the server. It contains some very useful data that let us update the cart.

Now, hit enter then wait a second and this is what we got back:

The Ultimate Guide To Adding Products To Cart Using Ajax In WooCommerce 7

The most important piece of data is the fragments. It is an array of objects. The key of each object is the css selector of cart-related element and the value of that key is the HTML content of that element.

Updating the cart now should be trivial. Consider it’s your homework 😉

Conclusion

As you can see, adding WooCommerce products via ajax is quite simple. With the knowledge you gain from this post (hopefully), I hope you can use it and make some awesome applications.

 

 

 

Posted on Leave a comment

WooCommerce Developer Cheat Sheet

This post is for WordPress/WooCommerce developer only. If you have problem implementing what I’m going to show you, please drop me a message.

How to get WooCommerce attribute label

There is a function for this purpose:

wc_attribute_label($attribute_name)

For example, the attribute name is pa_color, your name for this attribute is Color. The code above outputs “Color”

 

How to get WooCommerce Add to cart form

So currently, I’m developing a product table plugin for woocommerce. Initially, I used custom HTML code for the add to cart button. However, since I have another plugin that add styles to the add to cart button, I would love to just get the add to cart form from WooCommerce and use the styling from the custom add to cart plugin.

So, the question is how to get the Add to cart form output by WooCommerce?

It turned out, you can use this code to get the content of the form and store it in a variable:

ob_start();
                if ($this->productType == 'variable')
                {
                    wc_get_template( 'single-product/add-to-cart/variable.php', array(
                        'available_variations' => $this->product->get_available_variations(),
                        'attributes'           => $this->product->get_variation_attributes(),
                        'selected_attributes'  => $this->product->get_default_attributes()
                    ) );

                } else
                {
                    wc_get_template( 'single-product/add-to-cart/simple.php', array(

                    ) );

                }


                $data = ob_get_contents();

                ob_get_clean();

 

How to send add to cart request via ajax call and update the cart

In shop page, you will see that WooCommerce support ajax add to cart. When the customers click on add to cart button, the product is added to cart and the cart (normally at the top of the page/navigation) get updated. How can you do that?

First, you need to send an ajax request to the current url and add this:

?wc-ajax=add_to_cart

Then the parameters are:

{
product_id: id,
product_sku: "",
quantity: x
}

If it is a variable product, you need to include attribute data:

{
product_id: id,
product_sku: "",
quantity: x,
attribute_1: attribute_1_value,
attribute_2: attribute_2_value
}

Make sure you replace attribute_1/attribute_2 with actual attribute name.

Then, send the ajax request. If your request pass WooCommerce validation, the product will be added to cart and you will get this response:

wc-ajax-response

As you can see, it passes all the HTML needed and also the selectors for us to update the cart. At this point, you need to update the cart by replacing the HTML content for each elements returned in fragments.

Here is the sample code I have on my plugin:

$.post(window.location.href + "?wc-ajax=add_to_cart" , {data object here}, function(response){

    
    //update the cart
    try {
        let data = (response);
        _.each(data.fragments, function(content, index){
           $(index).html(content);
        });

    } catch (e) {
        console.log(e);

    }
});

If you now jQuery, the code above should be familiar. I use underscore to loop through all items in fragments and update HTML content for each element returned by WooCommerce.