The general idea
This whole idea is quite simple in its approach. Here's the logic broken down:
- Grab the current cart cookie value (and store it). It will be a 32 character UID string.
- Change the cart cookie value to something else.
- Add the product to the cart with AJAX (and wait). This will add the product to a new cart since we changed the cookie value.
- On success, call the shipping rate endpoint (and wait)
- On success, list out the values return (if any)
- Change the cookie value back to what it was returning the cart to its previous state.
Those 6 steps might seem like a lot but it's a far neater method to what I used to do. That old and gross method was to:
- Clear the cart,
- Add in the single product,
- Get the rates
- Clear the cart
- Add the previous products back in via AJAX
The new way removes any need to clear the cart or add the original products back in. We're just swapping the cart cookie back to it's original value instead. It all happens quickly in just a few AJAX calls keeping things as neat as possible.
Example / Demo
As usual there's a demo on the experiments site. To test this code, first add a bunch of random products to the cart, making sure the total cart value is bigger than $200. Any cart total above $200 will return a free rate and anything below will return a rate for $50. This is assuming that I've not changed the shipping rates since I wrote this post.
Once you've done that jump to the test product page. Scroll down towards the bottom to see the shipping rate calculator for a single product. Click get rates, leaving all the field values as is. Change the quantity on the product to 2 and try again. You'll see that the rate jumps between the free and $50 rate. Change it back to 1 and see the $50 rate show. Now check the cart and it should still have the bunch of products you initially added.
This code is quite specific to the theme I'm running on the experiments site, and the rates I have setup. Right now it's only good for inspiration but it's a cool proof of concept. Either copy the code from the block below or grab it from the Shopify Code Snippets repo.
grabbing the JS code...
What can go wrong
If the script fails during the process it might not switch that cart back to what is was, leaving the customer with only the current product in the cart.
It's also possible that two carts are created with the same value. I only use date time to generate a random string so it's not impossible for two users to click the button at the same time. A better solution would be to make it add another random number into the mix (or append a customer ID should they be logged in).
The code is there for you to improve on - not to copy and paste as is.