Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shopify cart changed event - javascript

Tags:

shopify

is there an event which is triggered when the shopify cart has changed. I can refresh the cart every x seconds to see if something has changed but an event based approach is always better.

like image 673
cloudpre Avatar asked Oct 15 '25 19:10

cloudpre


1 Answers

There isn't a one stop 'shopping' (he he) way to do it but it can be done.

In Shopify items are added to the cart either via a a regular HTML form POST to '/cart/add' or via Ajax so broadly speaking you'll need to account for both. Further, when using Ajax theme developers can either use the Shopify Ajax API or go for a straight up Ajax POST.

In the first case what you can do is add a submit handler to the form on page load so you'll be able to pick up the POST event just before the item is added.

In the second case where Ajax is being used via the Javascript wrapper API you can define a function which Shopify will call when the cart changes. E.g. suppose you defined this function:

Shopify.onCartUpdate = function(cart) {
  alert('There are now ' + cart.item_count + ' items in the cart.');
};  

The Ajax API will invoke it after items are added to the cart. You can check out the API sandbox to get a feel for it.

Finally there is the case where Ajax is being used directly. This the same scenario as this SO question and the accepted answer there where they work with the XMLHTTPRequest prototype methods look pretty good to me. If you are happy to use jQuery then using ajaxComplete would make it even simpler.

like image 102
Gavin Terrill Avatar answered Oct 18 '25 14:10

Gavin Terrill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!