Shopify - Displaying Cart Items On a Remote Website With Ajax

I wasn't too happy with the solutions out there using an iframe to show cart details on a remote website, so here's a solution to do it by using Ajax and JSON. I needed to display cart items in a drop down and it seemed too hacky of a solution to put a transparent iframe overlaying content on the site. If you're in the same position as me with having your Shopify site connected to a Wordpress site (or any other CMS for that matter) then here's how I did it!

Shopify generates a JSON file for your cart, it's formatted like so: If you access the URL you'll see the JSON output. Go ahead and try adding products into your cart and you'll see this file change. Now onto the code!

Setting Up Your Ajax call

You'll need to set up your ajax call first (I'm assuming you have jQuery included in your header already), notice for "dataType" you'll need to specify 'jsonp' since we are doing this cross domain. You can print the data in the console log just to double check it's working.

Check that there are items in the cart

Now that's working you can start pulling the data! First, let's make sure there are items in the cart. This way we don't need to make calls that are unnecessary.

Pull product data that has been added to the cart

Now let's get some product information. Typically you'll want to display the total count of items in the cart, which I appended to my Bag container. Simple enough.

Next, I wanted to display 2 cart items when a user hovered over the shopping cart icon/link, so I set up all of the variables I needed and a for statement. This is pretty much the entire ajax code you'll need.

Notice the 'STORE_URL' variable I used when linking the product URL. At the top of my js file I declared a global variable (this way it's accessible and you can use it if you're going to be doing more with the API) which was my Shopify site URL (i.e., since you're on a remote website you'll need to link to your products using the correct domain since the URL you get from JSON is a relative path.

Formatting Shopify Price with Javascript

Remember that Shopify displays the price in cents so you'll need to convert the cents to dollar amount by dividing your 'line_price' or 'price' (whichever one you're using) by 100, which will give you the whole dollar amount. To ensure the price will display correctly with a decimal and trailing cents (i.e. 5.50, not 5.5), you can use the 'toFixed' Method which I implemented above and here's the code below just for clarity sake.

This is pretty much the method I use to pull cart information onto a remote website. Let me know if you have any questions, suggestions, or other methods that you use, or if this helped you out!