6. Displaying the number of items in the cart when the product page is loaded

In theme.liquid, locate the <head> section. This is where we will be adding the Javascript to make it all happen.

First, we need to add create a variable called cartCount, which will store the number of items that are in the cart. When the product page is loaded, we want to query the number of items that are currently in the cart with Liquid, and then store it in a Javascript variable called ‘cartCount’.

  <script type="text/javascript">
  var cartCount = {{ cart.item_count }};
  </script>

Next, we want to create a function that is called upon when the page is done loading. When the page is loaded, the link with the id “cart-number” that we created in the last step should display the right number of items in the cart. We can do this by adding the the following function in the script:

  <script type="text/javascript">

  var cartCount = {{ cart.item_count }};

  $(document).ready(function(){
    {% if cart.item_count != 0 %}
       $('#cart-number').replaceWith("<a href='/cart' id='cart-number'>View cart (" + cartCount + ")</a>");
    {% endif %}
  });
  </script>

7. Make the AJAX call to add the product to the cart

Let’s now create the function for adding the product to the cart. Below the document.ready function, add the following function.

  <script type="text/javascript">

  var cartCount = {{ cart.item_count }};

  $(document).ready(function(){
    {% if cart.item_count != 0 %}
    $('#cart-number').replaceWith("<a href='/cart' id='cart-number'>View cart (" + cartCount + ")</a>");
    {% endif %}
  });

  function addItem(form_id) {
    $.ajax({
      type: 'POST',
      url: '/cart/add.js',
      dataType: 'json',
      data: $('#'+form_id).serialize(),
      success: addToCartOk,
      error: addToCartFail
    });
  }

  </script>

The addItem function makes an AJAX request using jQuery.ajax().

  • the type option specifies what kind of request we’re going to make. We will be making a POST request.
  • the url option tells the server to add the product to the cart.
  • the dataType option specifies the type of data that we want back from the server. We want to receive the data as JSON objects.
  • the data options specifies what data we want to send to the server. We’re going to be selecting the form from the product page, and using the serialize() method on it to make it into a string that is readable by the server.
  • If the AJAX call is successful, the addToCartOk function is called. If it is not, the addToCartFail function is called.

8. addToCartOk – the function for a successful AJAX call

Let’s start off by creating the function that is called when the product is added to the cart successfully.

      ...
      data: $('#'+form_id).serialize(),
      success: addToCartOk,
      error: addToCartFail
    });
  }

  function addToCartOk(product) {

    cartCount++;

    $('#added-box').html(product.title + ' was added to the cart!');
    $('#cart-number').replaceWith("<a href='/cart' id='cart-number'>View cart (" + cartCount + ")</a>");
    $.fn.colorbox({
      open:true, width: "400px", innerHeight: "60px", inline:true, href:"#added-box", transition: 'none'
    });
  }

Now, the lightbox that I created isn’t the prettiest thing in the world, but you can customize the look and feel by adjusting Colorbox’s properties. You can also modify colorbox.css.

To change the color of the overlay, open colorbox.css, and look for the #cboxOverlay selector and change the background to the color or image of your choice. To make my overlay black, I set #cboxoverlay to the following:

#cboxOverlay{background:#000;}

9. addToCartFail – the function for an unsuccessful AJAX call

The last thing we want to do is to create a function that is called if the product was not able to be added to the cart. The primary reason for not being able to add something to the cart is that there is not enough inventory for that item.

    ...
    $.fn.colorbox({
      open:true, width: "400px", innerHeight: "60px", inline:true, href:"#added-box", transition: 'none'
    });
  }

  function addToCartFail(obj, status) {
    $('#added-box').html('The product you are trying to add is out of stock.');
    $.fn.colorbox({
      open:true, width: "400px", innerHeight: "60px", inline:true, href:"#added-box", transition: 'none'
    });
  }
  </script>

Alternatively, you can use the code below to receive the actual message of the error. This was my initial approach, but I found that sometimes the Shopify servers won’t return the proper response, which in turn would not make the lightbox appear at all. If anybody could give me some insight on why this happens, that would be awesome.

    ...
    $.fn.colorbox({
      open:true, width: "400px", innerHeight: "60px", inline:true, href:"#added-box", transition: 'none'
    });
  }

  function addToCartFail(obj, status) {

    try {
    var response = jQuery.parseJSON(obj.responseText);
    $('#added-box').html(response.description);
    } catch(e) {
    $('#added-box').html("There was an error");
    }

    $.fn.colorbox({
      open:true, width: "400px", innerHeight: "80px", inline:true, href:"#added-box", transition: 'none'
    });
  }
  </script>

10. Conclusion

You now have a product page that works similar to that of Threadless. I’m not too happy with the way the addToCartFail function is working right now, but for now it seems like it’s the only way to have the lightbox appear every time there is an error. You can download the completed theme here.

Big thanks again to John Tajima for his help!

Pages: 1 2

6 Responses to “Creating a Threadless-like Add-to-Cart button using jQuery and AJAX”

  1. Keith on January 23rd, 2011

    does not work on Onyx theme.

  2. darbotron on February 1st, 2011

    Hey dude,

    Nice work :)

    I’ve done this same thing in mootools 1.3 (not the version that’s on the global asset area at shopify) if you’re interested in seeing the code just let me know.

    It makes no difference really, but I just prefer the way mootools code looks ;)

    darbotron

  3. Andrew on April 26th, 2011

    I’m having trouble getting this to work. Is there anything assumed you didn’t mention. Other scripts etc.. I’m using my own theme with this. Thanks

  4. Admin Image
    Tetsuro on April 27th, 2011

    Hey Andrew,

    Hmm… I don’t think I’ve left anything out. What’s your store’s URL? Maybe I can take a look and help out.

    Cheers,

    Tets

  5. Jamie on May 25th, 2011

    Hi Tets,

    I can’t figure out what I have done. I can’t seem to click add to cart at all now. Does it work with slate theme?

    I am not too familiar with js but your tut looked pretty straightforward so I gave it a go. Can you take a look at my shop for me? Password is unibox11 for the storefront. Need to get it sorted pretty soon as my launch is Tuesday.

    J

  6. Jason on November 2nd, 2011

    Darn! This looks so easy but I can’t seem to get it working.

    Any help would be appreciated. The store URL is https://littlehost.myshopify.com/ and the PW is ‘develop’ to view the shop.

    Thanks!

    - Jason

Leave a Reply:




Comment