2

I'm working on getting our site set up with Craft Commerce, and I am currently working on a sidebar cart for the site. I've found examples on how to add products to the cart using AJAX and jQuery and have gotten that working successfully. However, I'm struggling to understand how to update the cart listing after a successful response.

I have the sidebar cart template set up as an include. Is it possible to use AJAX and jQuery to reload just the sidebar cart include after the successful response? Or is there a better way to show the updated contents?

2

There are two main approaches in general to updating your page in response to changes in the cart.

The first is just an ajax load in of a partial template.

This is really just as simple as something like:

$cart.load("/_ajax-injects/cart.html").fadeIn('fast');

....which (assuming $cart points at a div holding your displayed cart) - would load in over the old cart a new cart (assuming templates/_ajax-injects/cart.html has such a partial template in it)

This is very easy to implement, but does not look wonderfully finessed as there will be a visible result of replacing a large section of the page at one go.

The second approach is using the json response.cart object to update just the appropriate fields within your already displayed cart.

This is considerably trickier. Each of the fields, such as your item quantities, subtotals, tax, shipping etc must have an identifying class or id on them, and then you parse through the response.cart object grabbing the appropriate values from that and inserting them into those fields. You also need to deal with e.g. removing lineItem rows if the qty is zero and so forth.

A lot more work, however once implemented this is a visually much more finessed approach as just the fields that need updating get updated.

  • Wow, the ajax is stupid simple. My problem was I was assuming I wouldn't be able to access the _includes since they're above the webroot. Thanks for the help! – Joel Apr 5 '17 at 13:50
  • I am getting 404 when trying to load the template. Do I need to reconfigure .htaccess or anything like that to make load work? The path to the template seems correct. – krizajb May 19 '18 at 19:46
  • I wasn't able to load files in folders with a _ prefix. – krizajb May 19 '18 at 22:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.