Product pages - Stay on the product page after adding products to the cart

TyW
Community Manager
451 63 1206

When a customer adds a product to the cart, some Shopify themes will take them to the cart page. This customization lets customers stay on the product page after clicking the Add to cart button, so that they can continue shopping.

 



prodpage01.jpg

Note: Most free Shopify themes include a setting that lets customers stay on the product page when a product is added to the cart. You can enable this in the theme editor, in either the Cart page settings, or the Product page settings. In the theme preview, navigate to the cart page to access the Cart page settings, or navigate to the product page to access the Product page settings.

 

 

Edit your theme code

 

 

To edit your theme code:

 

  1. From your Shopify admin, go to Online Store > Themes.
  2. Find the theme you want to edit, and then click Actions > Edit code.
  3. In the Layout directory, click theme.liquid.

    prodpage02.png

  4. Find the closing </body> tag. On a new line right above the closing </body> tag, paste the following code:

    {% render 'ajaxify-cart' %}

     


    prodpage03.png

  5. Click Save.
  6. In the Snippets directory, click Add a new snippet:

    prodpage05.png

  7. Name your snippet ajaxify-cart, and click Create snippet:

    prodpage06.jpg

    Your new snippet will open in the code editor.

  8. In your new ajaxify-cart.liquid file, paste this code hosted on GitHub.

    Caution: In the pasted code, replace all instances of .size() with .length. The .size() method is depreciated as of JQuery 1.8.

  9. Click Save.

 

Debut

 

 

If you use Debut, then continue to the next steps:

 

  1. In ajaxify-cart.liquid, find the opening <script> tag at the top of the file. On a new line right below the opening <script> tag, paste the following code:

    window.onload = function() {

     

  2. Find the closing </script> tag. On a new line right above the closing </script> tag, paste the following code:

    }

     

  3. In the same file, find the following code:

    cartCountSelector: '.cart-count, #cart-count a:first, #gocart p a, #cart .checkout em, .item-count',

     

  4. Replace it with:

    cartCountSelector: '#CartCount',

     

  5. Click Save.
  6. In the Sections directory, click header.liquid.
  7. Find the following code:

    {% if cart.item_count > 0 %}

     

  8. Replace it with:

    {% if cart.item_count > -1 %}

     

  9. Click Save.

 

Demo Store

 

 

Click here to view a demo store that lets customers stay on the product page when they add products to the cart.

TyW | Online Community Manager @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit the Shopify Help Center or the Shopify Blog

Replies 214 (214)

JosephGuerrero
Tourist
5 0 3

Hi! This does not seem to work for my debut themed site. I followed all the steps exactly and triple checked. 

 

Any ideas? Site URL: https://little-babes-bows.myshopify.com/

Marlan
Excursionist
20 0 0

Hi @JosephGuerrero 

 

Did you find any solution to this ? I also followed all steps and checked again many time but it still takes me to checkout 😞

 

Many thanks in advance 


@JosephGuerrero wrote:

Hi! This does not seem to work for my debut themed site. I followed all the steps exactly and triple checked. 

 

Any ideas? Site URL: https://little-babes-bows.myshopify.com/


 

arisw
Visitor
3 0 0

I am using the supply theme, it is still showing the checkout page after adding the product. Any solution?

Marlan
Excursionist
20 0 0

@arisw 

 

Did you follow all instruction on first page? I followed all instruction but it didn't work for me. Finally @Ninthony helped me out. He was very kind.

nezlinnoushad
Tourist
4 0 2

Hi! It works for me fine. Theme : Envy but the problem is it works only for products in home page. If I visit category pages and add to cart it still takes me to cart page. How do I enable this for all products site wide? please help. Thank you. 

Matt_Wilson-BPG
Excursionist
37 0 5

Same boat with this. Looking to get this to work store wide.

 

 

kjongrammart
Tourist
9 1 0

First of all thanks for the tutorial. It works perfectly on the Product Page. Im on a custom theme. 

However, 

I have the same need as @Matt_Wilson-BPG and @nezlinnoushad

Redirection only works in Product Page and not on Collections Page where we also manage to add the "ADD TO CART" button. It still redirects to Cart Page. How can we apply the solution to the  products under collections pages?

Can anybody help us? 


@Matt_Wilson-BPG wrote:

Same boat with this. Looking to get this to work store wide.

 

 


 

HandHugs
Shopify Expert
198 1 60

adding the ajax add to cart function to your collection and other store pages is more complicated and depends a LOT on your theme. You will probably need to hire a Shopify expert to do this for you, and I can't just explain how on the forum unfortunately. There are too many cases, specific codes and unique theme functions to post a 'one size fits all' solution here. 

nikolajjuuel
Visitor
1 0 1

Here is the code with all the updates added to it. Just paste it into the ajaxify-cart snippet section. You are most likely missing a '}' somewhere.


<script>
window.onload = function() {

/**
* Module to ajaxify all add to cart forms on the page.
*
* Copyright (c) 2015 Caroline Schnapp (11heavens.com)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
Shopify.AjaxifyCart = (function($) {

// Some configuration options.
// I have separated what you will never need to change from what
// you might change.

var _config = {

// What you might want to change
addToCartBtnLabel: 'Add to cart',
addedToCartBtnLabel: 'Thank you!',
addingToCartBtnLabel: 'Adding...',
soldOutBtnLabel: 'Sold Out',
howLongTillBtnReturnsToNormal: 1000, // in milliseconds.
cartCountSelector: '#CartCount',
cartTotalSelector: '#cart-price',
// 'aboveForm' for top of add to cart form,
// 'belowForm' for below the add to cart form, and
// 'nextButton' for next to add to cart button.
feedbackPosition: 'nextButton',

// What you will never need to change
addToCartBtnSelector: '[type="submit"]',
addToCartFormSelector: 'form[action="/cart/add"]',
shopifyAjaxAddURL: '/cart/add.js',
shopifyAjaxCartURL: '/cart.js'
};

// We need some feedback when adding an item to the cart.
// Here it is.
var _showFeedback = function(success, html, $addToCartForm) {
$('.ajaxified-cart-feedback').remove();
var feedback = '<p class="ajaxified-cart-feedback ' + success + '">' + html + '</p>';
switch (_config.feedbackPosition) {
case 'aboveForm':
$addToCartForm.before(feedback);
break;
case 'belowForm':
$addToCartForm.after(feedback);
break;
case 'nextButton':
default:
$addToCartForm.find(_config.addToCartBtnSelector).after(feedback);
break;
}
// If you use animate.css
// $('.ajaxified-cart-feedback').addClass('animated bounceInDown');
$('.ajaxified-cart-feedback').slideDown();
};
var _setText = function($button, label) {
if ($button.children().length) {
$button.children().each(function() {
if ($.trim($(this).text()) !== '') {
$(this).text(label);
}
});
}
else {
$button.val(label).text(label);
}
};
var _init = function() {
$(document).ready(function() {
$(_config.addToCartFormSelector).submit(function(e) {
e.preventDefault();
var $addToCartForm = $(this);
var $addToCartBtn = $addToCartForm.find(_config.addToCartBtnSelector);
_setText($addToCartBtn, _config.addingToCartBtnLabel);
$addToCartBtn.addClass('disabled').prop('disabled', true);
// Add to cart.
$.ajax({
url: _config.shopifyAjaxAddURL,
dataType: 'json',
type: 'post',
data: $addToCartForm.serialize(),
success: function(itemData) {
// Re-enable add to cart button.
$addToCartBtn.addClass('inverted');
_setText($addToCartBtn, _config.addedToCartBtnLabel);
_showFeedback('success','<i class="fa fa-check"></i> Added to cart! <a href="/cart">View cart</a>',$addToCartForm);
window.setTimeout(function(){
$addToCartBtn.prop('disabled', false).removeClass('disabled').removeClass('inverted');
_setText($addToCartBtn,_config.addToCartBtnLabel);
}, _config.howLongTillBtnReturnsToNormal);
// Update cart count and show cart link.
$.getJSON(_config.shopifyAjaxCartURL, function(cart) {
if (_config.cartCountSelector && $(_config.cartCountSelector).length()) {
var value = $(_config.cartCountSelector).html() || '0';
$(_config.cartCountSelector).html(value.replace(/[0-9]+/,cart.item_count)).removeClass('hidden-count');
}
if (_config.cartTotalSelector && $(_config.cartTotalSelector).length()) {
if (typeof Currency !== 'undefined' && typeof Currency.moneyFormats !== 'undefined') {
var newCurrency = '';
if ($('[name="currencies"]').length()) {
newCurrency = $('[name="currencies"]').val();
}
else if ($('#currencies span.selected').length()) {
newCurrency = $('#currencies span.selected').attr('data-currency');
}
if (newCurrency) {
$(_config.cartTotalSelector).html('<span class=money>' + Shopify.formatMoney(Currency.convert(cart.total_price, "{{ shop.currency }}", newCurrency), Currency.money_format[newCurrency]) + '</span>');
}
else {
$(_config.cartTotalSelector).html(Shopify.formatMoney(cart.total_price, "{{ shop.money_format | remove: "'" | remove: '"' }}"));
}
}
else {
$(_config.cartTotalSelector).html(Shopify.formatMoney(cart.total_price, "{{ shop.money_format | remove: "'" | remove: '"' }}"));
}
};
});
},
error: function(XMLHttpRequest) {
var response = eval('(' + XMLHttpRequest.responseText + ')');
response = response.description;
if (response.slice(0,4) === 'All ') {
_showFeedback('error', response.replace('All 1 ', 'All '), $addToCartForm);
$addToCartBtn.prop('disabled', false);
_setText($addToCartBtn, _config.soldOutBtnLabel);
$addToCartBtn.prop('disabled',true);
}
else {
_showFeedback('error', '<i class="fa fa-warning"></i> ' + response, $addToCartForm);
$addToCartBtn.prop('disabled', false).removeClass('disabled');
_setText($addToCartBtn, _config.addToCartBtnLabel);
}
}
});
return false;
});
});
};
return {
init: function(params) {
// Configuration
params = params || {};
// Merging with defaults.
$.extend(_config, params);
// Action
$(function() {
_init();
});
},
getConfig: function() {
return _config;
}
}
})(jQuery);

Shopify.AjaxifyCart.init();
}
</script>

{% comment %}
If you want to animate your feedback message.
{% endcomment %}

{% comment %}
{{ '//cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.0/animate.min.css' | stylesheet_tag }}
{% endcomment %}

{{ '//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.0.3/css/font-awesome.css' | stylesheet_tag }}

<style>
.ajaxified-cart-feedback {
display: block;
line-height: 36px;
font-size: 90%;
vertical-align: middle;
}
.ajaxified-cart-feedback.success {
color: #3D9970;
}
.ajaxified-cart-feedback.error {
color: #FF4136;
}
.ajaxified-cart-feedback a {
border-bottom: 1px solid;
}


</style>

kjongrammart
Tourist
9 1 0
Hi Niko,

I really appreciate this. Quick question though since Im no coding expert
at all. Do I need to
1. Replace all the contents of the snippet section
2. Jut replace a portion
3. Paste all these at the bottom of all the contents.

Kindly enlighten me sir.

Regards,
Kris




demisharon
Visitor
1 0 0

Hi there,

Thanks for sharing the updated code. I'm now however having the issue that I'm taken to the product page whenever I want to select the quantity prior to adding to cart on the shop/collection page. My site url is flwr-co-cookies.myshopify.com (password: veganisthefuture). I'm completely new to coding so if anyone has a solution for this, please let me know ASAP!

LLSHOP11
Visitor
2 0 0

I had the same issue with Debut, but I fixed it and got it to work!

1. First, go under 

ajaxify-cart.liquid

and hold down command + F and type in .size() in the search bar, make sure all the .size() are replace with .length. 

It should look like .length)

(I was missing two of them, make sure there is only one ending bracket ")" )\

2. Next, make sure you do not have any extra commas, I had 1 extra comma when I pasted the cartCountSelector: '#CartCount',

Once I fixed those, it worked! Good luck. 

 

thebrightbeaver
Visitor
1 0 0

Try checking the apps linked to your page. It is likely you may have enabled the Accelerated Checkout function, hence causing such an issue, rather than the codes.

CPerry
Tourist
4 0 3

Hi! Have there been any updates to this at all? I'm using the Debut theme and I've followed these instructions exactly and triple checked it all. I still get sent to the cart when adding a product.

Ardi94
Shopify Partner
104 3 32

Work great, thanks

@CPerry @JosephGuerrero 

If you want to send your codes here I might be able to help you out

CPerry
Tourist
4 0 3

@Ardi94  I was actually able to get this working last night but I ran into some other issues. When I remove the "defer" portion (as referenced in the comment in this post) from the theme.liquid file, my slideshow and dropdown navigation stop working. If I leave the "defer" portion, the add-to-cart functionality doesn't work and I get redirected to the cart anyway.

 

I'm trying to sort this out and see if I can find another way to get this working!

PurelyTru
Visitor
2 0 16

I have also been trying to do this same thing for days now

 

FINALLY found something that worked

 

Follow the process for everything above. If you click Add To Cart, and it still takes you to the checkout page then try this

 

In your theme.liquid file

 

Add:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

 

Right above: 

{% render 'ajaxify-cart' %}

 

This worked for me and was the only minor step missing from this guide 

robbin
Tourist
4 0 1

Applied this fix as I was having the same issues.  What's happening now is that it's still going to the cart but there's like a 2 second pause before it goes to the cart.  Any ideas?

ashleystephens
Visitor
2 0 2

Tried this and no luck. Any suggestions?

Chevron_Editing
Visitor
1 0 1

Adding <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></scriptsolved it for me as well - I'm using Venture.  Thanks for posting! 

 

 

aymanemad
Tourist
13 0 2

Where can I add it?

Lux8
Excursionist
16 1 5

Hi

I've followed all the instructions and added the script code but it still has a short lag before taking me to the cart. Does anyone have a fix for this?

HandHugs
Shopify Expert
198 1 60

with this code implemented correctly, it should not take you to the cart anymore. There is probably an error somewhere in the implementation of the code. 

Nrotlisberger
New Member
7 0 0

Could you tell me where to implement the code once more?

muarvelous
Visitor
2 0 0

PERFECTION!!! 

jrgreenboylawn
Visitor
1 0 0

This worked for me!  Thank you!  

However, is there a way for the customer to stay in the same collection that they were in, rather than go to a generic products page that contains all the products I sell all jumbled together in no particular order?  Thanks,  Jeremiah

colleenc
Shopify Partner
82 7 20

One way would be to remove that line of code completely. Search in the code for the phrase "continue shopping" and just delete that line.

TheWreckShop
Tourist
8 0 0

Thank you so much. That really fixed 1 of my 2946520933452049875293 problems in my list. 

Now I will try to change the look of my ADD TO CART ....

And I need to fix the number of products added in the shopping icon (it  simply VANISHED.)

Do you have any idea how can I fix these two problemas too?

 

Thank you anyway. 

 

DanGlazenburg
Tourist
6 0 2

This worked perfectly for me on the preview page, but when i made the theme published it did not.

I removed the line and re-tested it... It worked perfectly without the code?? lol?

DanGlazenburg
Tourist
6 0 2

Update - when publishing it works with all the code, including the google API

Nubi-Han
New Member
4 0 0

Hi Dan,

Thanks so much for your reply.

I downloaded a fresh copy to check the version, and it is "theme_version": "17.6.0", which is the one I am am currently using..

Also my site is published, just password protected.

Do you have any other suggestions at all - sorry to be a pain!

 

NH x

DanGlazenburg
Tourist
6 0 2

Try without password protection to see if that's causing the issue.

I'm using 17.13.0 downloaded today... I had to rebuilt today due to an app decommissioning, causing my backup products file being overwritten and unfixable...

I also put a bunch of breaks (just pressing enter, not <br>) between the google API and the Ajax render.

Nubi-Han
New Member
4 0 0

Ouch, sorry to hear that.

I'm trying to avoid a re-build unless absolutely necessary - I haven't customised massively but i'm so close to going fully live. This is the last big hurdle..

Thanks for the password tip - I tried disabling but unfortunately that didn't work either.

This is a big ask, and no worries if not, but would you mind DM'ing me your theme and ajaxify-cart.liquid code from a working / non-redirecting version? I'd like to check if there are any discrepancies.

 

Thanks,

NHx

ekanta
Visitor
1 0 0

still it takes me to cart page , any fixes

 

SameedAnis
Visitor
3 0 0

Hi, I tried the above code as well, did not work. I am running a debut theme.

imdesigns
Shopify Partner
10 0 0

did that and it still didn't work in Debut

Marlan
Excursionist
20 0 0

Hi @CPerry 

 

Would you mind advising how you fixed " Staying on the product page after adding products to the cart" in Debut theme ? I followed all instructions but it still takes me to the checkout 😞

 

Many thanks in advance 


@CPerry wrote:

@Ardi94  I was actually able to get this working last night but I ran into some other issues. When I remove the "defer" portion (as referenced in the comment in this post) from the theme.liquid file, my slideshow and dropdown navigation stop working. If I leave the "defer" portion, the add-to-cart functionality doesn't work and I get redirected to the cart anyway.

 

I'm trying to sort this out and see if I can find another way to get this working!


 

Kareema
Tourist
10 0 4

hello ! in my debut theme it is working fine until I click on a "load more" button in my collection page. all products in my collection page has an add-to-cart button , all of them work fine with this ajaxified version. only when I click load more button and then add to cart a product from the newly loaded group, the page is being refresh; hence not showing ajax feature! Need help here!!

Kareema
Tourist
10 0 4

However I could solve the issue. So in my debut theme all is working fine !

ErinnLaMattery
Shopify Partner
8 0 1

I followed the tutorial and the product is successfully added to the cart and I stay on my product page. However, I am unable to add another product to the cart, the 'ADD TO CART' button is null until I refresh the page. 

I use Brooklyn. Has anyone had this problem and figured out a solution? 

PureTime
Explorer
66 2 22

It worked for me in the Minimal Theme.

However, I did a small change to make it support multi-language:

I changed this:

addToCartFormSelector:         'form[action="/cart/add"]',

 

To this:

addToCartFormSelector:         'form[action*="/cart/add"]',

 

I also made a style-change to look it more like a 'drawer style' (coming from top) with a small animation. You can see it in action here (by adding a product to the cart):
https://puretime.dk/en

PureTime
Explorer
66 2 22

Sorry, I changed the functionality - but here is a recording of how the overlay tweak looked.

ErinnLaMattery
Shopify Partner
8 0 1

Very cool, I'll give that a try!

 

Update, I made that small change to my code, but it didn't solve the problem, I have to refresh my page after adding to cart to get the Add to Cart button to function again. Hmmmm.

SameedAnis
Visitor
3 0 0

Hi Ardi94. I tried this for my store which has been made on the debut theme. It is still taking me to the add to cart page.

 

SameedAnis
Visitor
3 0 0

Hi, I am facing the same issue. Any suggestions on how to fix this?

imdesigns
Shopify Partner
10 0 0

do you know what issue is? Using Debut as well and this didn't work at all

robbin
Tourist
4 0 1
I’m sure this would work for other themes as well