Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

I am assuming you want to know when a customer's cart is changed which is technically on two basis :

  • there is cart created whenever first add to cart event happens
  • when a user completes a transaction and then the next time he/she visits the store and adds anything to their basket then a new cat is created.

When a cart is created an id is assigned to it and it has an expiration which is set in cookie with name "cart" this token is also delivered in webhook post callbacks as id and cart_token in carts_update and checkout event.

So to check to when a new cart is created you can do something like :

shopifyCart = function() {//call this on page load
var cartCookie = getCookie('cart');//Get shopify cart cookie
if( cartCookie !== undefined && cartCookie !== '' )
{
  if( cartCookie !== getCookie('key') )//reference key 
  {
      setCookie('key', cartCookie);//set cookie for next time comparison
      //Do your action on the event
  }
}
};

No. There is no native event broadcast when the cart changes. You are free as a bird to wire up your own listener to your own events. Since you can control what goes into the cart, you can thus control what happens on changes. The API is decent and there is plenty of free code kicking around in Prototype, Moo and jQuery to suit most devs taste.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top