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. It was a good idea for new WooCommerce tutorial post.
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();
});
});
To avoid an errors with refreshing the card fragment, will be better to create a new 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. I meant that you donโt need to edit the add-to-cart template file for grouped and variable products. Everything will work without additional code.
Do you want to see how it works?
Tags: Tutorials
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
Alex Podolyan
| #
Hello,
Just replace this code snippet
Reply
Anil
| #
Hi alexnet,
Thank you very much for your help. The code you gave worked perfectly as I wanted.
Thanks againโฆ
Reply
Tani
| #
awesome!
Reply
dinesh
| #
great article and code working fine .. ๐
Reply
irv
| #
Hey you mentioned that “For grouped and variable products, we donโt need to do it”, what do you mean by that?
is there additional codes we need to add to achieve this effect for variable products?
Reply
Alex Podolyan
| #
I meant that you don’t need to edit the add-to-cart template file for variable products. Everything will work without additional code.
Reply
Fabio
| #
Nice tutorial, thanks!
Reply
Karthick K
| #
In which file we have to add all these snippets
Reply
Alex Podolyan
| #
Hello,
If your theme has a field for custom JS code, use it. You can also add this code to the main JS file of your theme via FTP.
Best, Elartica Team
Reply
Denis
| #
Alexs you speak Russian?
Reply
Alex Podolyan
| #
Hello Denis,
Yes, I speak Russian. If you have any questions please write to this e-mail elartica.hub@gmail.com
Best Regards, Elartica Team
Reply
Russell
| #
I tried your code, and I’m getting an error in my console: TypeError: $ is not a function – Where have I gone wrong? I pasted your code into a JS snippets plugin for WordPress. Here’s my dev site: http://p1l3str3d3t.denflyvendetallerken.no
Reply
Russell
| #
Okay, I moved the js from the footer to the header, and now I get the error: ReferenceError: wc_cart_fragments_params is not defined
Reply
Alex Podolyan
| #
Hello Russell,
You need to read how to use jQuery correctly ๐
jQuery(function($){
/*insert my code*/
});
Reply
Alex Podolyan
| #
And what about wc_cart_fragments_params…
First you need to add the code to update the cart fragments in the functions.php file.
Here is an example of how I did it.
Reply
Stoil Kostadinov
| #
Thank you for your good article. I have just tried the code with latest WordPress version (4.9.5) and Woocommerce version (3.3.4) as of this moment and the code seems to be working fine. In my case I had to do some other modifications because I am using this for a Product quick view custom functionality and not for the single product page but still your snippet works just fine.
Keep up the good work!
Reply
Alex Podolyan
| #
Thank you so much for your kind words.
Reply
Jason
| #
Alex, nice write-up. I tried to use the code on a client site where I’m using WooCommerce Product Addons. In this case, its tickets for adults and children. When I view my mini cart (also Ajax) the quantity of tickets is correct, but not the price.
Any suggestions?
Thank you again, I will be using this code in the future.
Reply
Alex Podolyan
| #
Thanks! ๐
Please, read this post, maybe one of your extensions that you use on the site changes the cart meta data (I mean the price)
Reply
Jason
| #
Alex, my apologies. I am stupid. I was using the wrong product addon type. I used custom field “number” instead of “additional price multiplier.” It works great. A few CSS issues to work out, and I will be implementing this solution on my current project.
Thank you very much.
PS – It is worth noting that your solution DOES work with product addons, and is the only one I have found which does. Thank you again.
Jason
Reply
Alex Podolyan
| #
Well, I’m glad I was helpful.
Reply
Ilchy
| #
Great article, help solve my issue. Latest version of WP and WOO, with twentysixteen theme. Howver, I have to change your function to from this:
TO
Added the “?” part Looks like it’s working now, keep it up!
Reply
Ilchy
| #
Spoke too soon. Just trying to get it to work with WP twentysixteen theme – fresh installs of WOO and WP. And I just can’t get it to update the products ๐ Any ideas?
Reply
Alex Podolyan
| #
Do you mean that adding to the cart works well but the products in the mini cart widget aren’t updated? I didn’t quite understand your question
Reply
Mayur
| #
Hi add to cart ajax is working on single page but it is not updating mini cart
please assist in this
Reply
Alex Podolyan
| #
Hello,
If you use custom mini cart widget, you need to add cart fragments for updates using ajax. Here’s how I did it in my themes.
Reply
Deepa
| #
I want to add ajax add to cart button on individual product page. I have gone through your code and add it into my theme but nothing happens. Could you please guide where to add your code as i am helpless and any help would be appreciated.
Reply
Alex Podolyan
| #
Hello Deepa,
Can you send me link to the page, FTP and admin access on the my e-mail elartica.hub@gmail.com
I’ll try to help you do this.
Best, Alex
Reply
Mityay
| #
Hello, thanks for the article. Help me with woocommerce error message, how it get, please
Reply
Alex Podolyan
| #
Hello,
Do you mean the message that the product have been added to the cart?
Reply
Mityay
| #
No, if count product in cart equal quantity in stock, then woocommerce-error
Reply
Alex Podolyan
| #
It does not matter which message status (error or successful). You need to add a few lines of code to display the result of the ajax request.
How to do this I described in this comment https://elartica.com/2017/08/03/woocommerce-ajax-add-cart-single-product-page/#comment-4
Reply
Liam
| #
You don’t need to modify the add to cart template (PHP) if you make this the javascript
It adds the name and value of the submit button to the request payload which makes it work without changing the template file.
Reply
Alex Podolyan
| #
Thank you, your solution works fine for me. I optimized your code a little.
Reply
Guntur
| #
i couldnt find where to input / edit this code. any help please? thanks
Reply
Alex Podolyan
| #
Hello,
This JS code you can add to the main JS file of your theme. If you use Divi, you can add this code in the custom JS code field on the Divi settings page.
Depending on what framework you use it can be done in different ways.
Reply
Pinank shah
| #
Hi,
I inserted the code in the Footer Javascript Code Section. But it still ain’t working. Can you pls. help. The product type is Grouped. Thank you in anticipation
Reply
Alex Podolyan
| #
If you want all jQuery methods to work correctly, you need to add their inside a document ready event or function. You can find more information on this page https://www.w3schools.com/jquery/jquery_syntax.asp but I like to do something like that
Reply
Alexandros Skafas
| #
Hey Alex,
I am trying to make it work on my theme but i cant is it possible to give me a hand?
Reply
Alex Podolyan
| #
Hi,
Can you send me a link to the site or test page and FTP access on the my e-mail elartica.hub@gmail.com
Iโll try to help you.
Best, Alex
Reply
Michael Chamberlain
| #
Hey, nice article, and just a side note, but I love the theme you use on the demo … what theme is it? link: http://deepsoul.elartica.com/women/stuff/ossature-clock/
Reply
Michael Chamberlain
| #
Scratch that request, of course …deep soul Ha!
Reply
Alex Podolyan
| #
This is the premium WordPress theme that we sell on themeforest. I’m very glad that you like.
Reply
Pavel
| #
Thank you very much for this easy-to-go article. It is simple and very helpfull!
Reply
Alex Podolyan
| #
Thank you for the nice words. I’m always glad to help
Reply
Subraa
| #
Great information!!
I have use this code in my website and it is working fine without any error.
Reply
Charidimos Tzedakis
| #
The code works perfectly! Thanks a lot for posting this valuable help! ๐
Reply
Samuel Bassah
| #
That’s an amazing write-up and the codes you have there. It works for me on a single page. Thanks. However, I want to know if it’s possible to edit the javascript to also allow the same feature to work on the archive page. Enabling ajax add to cart on the archive page with custom add to cart button. Below is my code for the custom button. Can you help with that please?
`/**
* Override loop template and show quantities next to add to cart buttons
*/
add_filter( ‘woocommerce_loop_add_to_cart_link’, ‘quantity_inputs_for_woocommerce_loop_add_to_cart_link’, 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
if ( $product && $product->is_type( ‘simple’ ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
$html = ‘add_to_cart_url() ) . ‘” class=”cart” method=”post” enctype=”multipart/form-data”>’;
$html .= woocommerce_quantity_input( array(), $product, false );
$html .= ‘get_id() ).'” />’;
$html .= ” . esc_html( $product->add_to_cart_text() ) . ”;
$html .= ”;
}
return $html;
}`
Reply
Alex Podolyan
| #
Hi Samuel,
Sorry for the late reply.
I have another solution for this task ๐
If you want to add a quantity field on the products list pages, that’s what I did in your place.
And after this add the JS code for changing the quantity parameter on the add to the cart button. It looks like this to me, but you can have other selectors, so be vigilant.
Reply
Peter
| #
Hi Alex,
excellent tutorial and it worked perfect, it was what I was looking for.
I’m just asking a question, I would like this solution to work in the pop up of the quick view. What changes should I make?
a big hug!
Reply
Alex Podolyan
| #
Hello Peter,
If the add to cart form in the modal window has a parent with a class ‘.entry-summary’, then everything should work. So, you need to check all the parent elements of the add to cart form in the modal window, one of them must have this class ‘.entry-summary’
Best Regards, Alex
Reply
Valeria
| #
Hi Alex,
Thanks for the tutorial. It worked fine.
I would also like to update the number of products in the cart that I display in the navigation, and show a little notification, same as I can see in your demo.
I saw the snippet that you provided in one of the comments, but did not quite understand how it works. I replaced
with
but all it did is replaced the whole “
<span class="counter">1</span>
” with just the number of items in the cart, and it does not update when I click the button.Could you help with that (update the number and show a notification)?
Thank you in advance.
Reply
Alex Podolyan
| #
Hello Valeria,
Sometimes we need to change the mini-cart.php Woo template for some projects. So if we need to change the content in our mini cart using AJAX, such as the products count in the cart or the total price, we need to use $fragments. In this case, the key of array item is the selector of HTML element.
When you talked about the notification you meant the notification that the product was successfully added or about something else. What did you mean?
Best Regards, Alex
Reply
Fabian
| #
Hi Alex,
I guess this is not working for products with variations, right?
Regards, Fabian
Reply
Alex Podolyan
| #
Hello Fabian,
It’s works well for variation products too, you can check it on this page http://deepsoul.elartica.com/accessories/scarf/
Best Regards, Alex
Reply
Fabian
| #
Cannot get this to work on my site. If I click the “add to cart” button. Nothing happens.
Reply
Alex Podolyan
| #
If you want I can help you add this, but you need to send me FTP access and link to the site. You can use contact form for this.
Reply
Chris Dark
| #
Hi Alex,
I read this wc_cart_fragments_params is deprecated and now we should use woocommerce_get_script_data, how should we change the code?
Alex Podolyan
| #
Hi Chris,
You’re right, a wc_cart_fragments_params filter is deprecated since WooCommerce 3.3. But in this tutorial I didn’t use this filter, I just used one of the parameters (wc_ajax_url) for the fragments refresh function.
This filter was used to add or edit parameters of the cart fragments and now it can be done like this.
Best Regards, Alex
V
| #
Alex, awesome code!! Quick question though, with this new code, there is no validation on the variations form anymore. So even if the user has not selected any options from the variations attribute dropdowns, no validation message is shown. Thoughts?
Reply
Alex Podolyan
| #
Hello,
If you check an example on this page http://deepsoul.elartica.com/accessories/scarf/ you will see that the add to cart button is not active, only after the variation is selected can you add the product to the cart.
I also have an example of how to add a notification to the page after ajax action https://elartica.com/2017/08/03/woocommerce-ajax-add-cart-single-product-page/#comment-4 , I am sure it will help you to do what you want.
Best, Alex
Reply
John
| #
This works perfect! Thanks a lot.
Reply
Mohammad
| #
Hi. Many thanks. Works fine for me
Reply
Ralph
| #
I tried implementing the code, seems to work but when I tried adding quantity, it only saves one item.
Reply
Alex Podolyan
| #
Hello Ralph,
I assume you have changed the default template for selecting the quantity, Iโm sure that the reason for this is for some reason the script doesn’t get the product quantity in the field and applies the default value of 1
Reply
Bunty
| #
***** #Where to add this code #*****
// 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();
});
});
Reply
Alex Podolyan
| #
There are several ways to do this, add to the main JS file of your theme, install the plugin and add the code to the site header, add it o the main JS file your child theme files, it all depends on the stack you are working with.
Reply
Bunty
| #
hey, alex, first thank too u, code is working , only problem is, when i click
on add to cart, loader not work , like your demo. and even added cart message not showing.
jQuery(document).ready(function($){
// 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),
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
Omid
| #
Thank you Alex! This was very nice tutorial for me but beside main point of this tutorial I have noticed very interesting item in your demo page which made me curious! I am really interested to know how the “Product Added” notification, below the cart icon is implemented on your demo? Is there any tutorial for it?
Reply
Alex Podolyan
| #
Hi, there!
I think that no tutorials are needed for this, I just copied the layout of the mini cart into my theme and added a block with the text that the product was added to the cart. To make everything work correctly, I added two states, active and inactive for this block (using the class). You just need to add before $(‘.entry-summary’).unblock(); add something like it
Reply
Omid
| #
Thanks! It works like a charm.
Reply
Omid
| #
Hi Alex!
It seems this code ( Ajax add to cart ) is not compatible with WooCommerce 5.5.1, do you have any similar experience?
Reply