Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to Cart using AJAX in Shopify

By default, when you add a product to a cart in Shopify, it will redirect you to the Cart page. What I want to do is have it add to the cart without refreshing the page at all.

Shopify provides some instructions on how to do this here: http://docs.shopify.com/support/your-website/themes/can-i-use-ajax-api, but I am pretty unfamiliar with AJAX, so it's giving me a bit of trouble.

They provide a JavaScript file (http://cdn.shopify.com/s/shopify/api.jquery.js?a1c9e2b858c25e58ac6885c29833a7872fcea2ba) with some functions, the principle ones being:

// -------------------------------------------------------------------------------------
// POST to cart/add.js returns the JSON of the line item associated with the added item.
// -------------------------------------------------------------------------------------
Shopify.addItem = function(variant_id, quantity, callback) {
  var quantity = quantity || 1;
  var params = {
    type: 'POST',
    url: '/cart/add.js',
    data: 'quantity=' + quantity + '&id=' + variant_id,
    dataType: 'json',
    success: function(line_item) { 
      if ((typeof callback) === 'function') {
        callback(line_item);
      }
      else {
        Shopify.onItemAdded(line_item);
      }
    },
    error: function(XMLHttpRequest, textStatus) {
      Shopify.onError(XMLHttpRequest, textStatus);
    }
  };
  jQuery.ajax(params);
};

and

// ---------------------------------------------------------
// POST to cart/add.js returns the JSON of the line item.
// ---------------------------------------------------------
Shopify.addItemFromForm = function(form_id, callback) {
    var params = {
      type: 'POST',
      url: '/cart/add.js',
      data: jQuery('#' + form_id).serialize(),
      dataType: 'json',
      success: function(line_item) { 
        if ((typeof callback) === 'function') {
          callback(line_item);
        }
        else {
          Shopify.onItemAdded(line_item);
        }
      },
      error: function(XMLHttpRequest, textStatus) {
        Shopify.onError(XMLHttpRequest, textStatus);
      }
    };
    jQuery.ajax(params);
};

I'm really not positive which one is better to use for what I'm trying to do, so I've tried both. First, I tried to arrange my product submit form like this:

<form action="/cart/add" method="post" class="clearfix product_form" data-money-format="{{ shop.money_format }}" data-option-index="{{ option_index }}" id="product-form-{{ product.id }}">
    // yadda yadda
    <input type="submit" name="add" value="Add to Cart" id="add-to-cart" class="action_button" onclick="return false; Shopify.addItem({{variant.id}}, 1, 'okay')"/>
</form>

Where I just added the onclick="return false; Shopify.addItem({{variant.id}}, 1, 'okay')" to the input (return false to prevent redirect and the Shopify.addItem function to add the item via Ajax.) Neither of those things actually work.

I've also tried:

<form action="/cart/add" method="post" class="clearfix product_form" data-money-format="{{ shop.money_format }}" data-option-index="{{ option_index }}" id="product-form-{{ product.id }}">
    // yadda yadda
    <input type="submit" name="add" value="Add to Cart" id="add-to-cart" class="action_button" onclick="Shopify.addItemFromForm({{variant.id}}, 'okay')"/>
</form>

This also seems to have no effect.

They provide a demo page for their Ajax here: http://mayert-douglas4935.myshopify.com/pages/api

And when I try and copy the code for their Shopify.addItemFromForm example, it gives me this error alert when I try and add to cart: "Cart Error(400): We were not able to add this item to your shopping cart because no variant ID was passed to us. (request_id: 864f24c82d1bfbae4542a9603674861e)"

What am I doing wrong? Am I using the wrong functions? Am I passing the wrong arguments? I've been trying different variants of the above for 2 days now, and I haven't made any noticeable progress. Any help is greatly appreciated.


Update Resolved it with some tinkering and Steph's answer. The code that worked:

{% if product.options.size > 1 %}
       <a onclick="Shopify.addItem($('#product-select-{{ product.id }} option:selected').val(), 1); return false" href="#">Add Item</a>
      {% elsif product.options.size == 1 and (product.variants.size > 1 or product.options[0] != "Title") %}
       <a onclick="Shopify.addItem($('#product-select-{{ product.id }} option:selected').val(), 1); return false" href="#">Add Item</a>
      {% else %}
       <a onclick="Shopify.addItem({{ product.variants.first.id }}, 1); return false" href="#">Add Item</a>
      {% endif %}

First two conditions check if product has options, if so, get variant value from the selected option. The else is for items with no options, and {{ product.variants.first.id }} gets the correct variant id.

like image 866
damon Avatar asked Dec 17 '13 19:12

damon


People also ask

What is AJAX cart in Shopify?

Ajax add to cart is a feature that allows users to add products to their shopping cart without having to refresh the page. This makes for a faster and more user-friendly shopping experience. Shopify is a platform that allows businesses to create and manage their online stores.

How do I add add to cart button Shopify?

To start, log into your Shopify admin and go to Online Store > Themes. Find the theme you want to edit and click Customize. On the left-hand side of the Customize theme page, you'll see a section called Cart. Under Cart, you'll see an option called “Add to cart” button.


2 Answers

I think you want to be using Shopify.addItem and not Shopify.addItemFromForm (unless of course you have your variant id and quantity in a form that you want to use).

Here's an example of both ways. I modified the code from the demo page you linked to in your question.

Shopify.addItem:

<a onclick=" Shopify.addItem(jQuery('#product-select option:selected').val(), 1); return false" href="#">Shopify.addItem</a>

Shopify.addItemFromForm:

<form id="add-item-form" method="post" action="#">
    variant: <input class="update" type="text" value="324748289" name="id" size="8">
    qty: <input type="text" value="1" name="quantity" size="3">
</form>
<p>
    <a onclick=" Shopify.addItemFromForm('add-item-form'); return false" href="#">Shopify.addItemFromForm</a>('add-item-form')
</p>

A couple of things to check in your code:

  • Is {{variant.id}} returning the correct value for the currently selected variant?
  • The Shopify.addItemFromForm function takes a form id as a parameter, not a variant id.
like image 96
Steph Sharp Avatar answered Sep 27 '22 17:09

Steph Sharp


it's to much easy just following these steps : Step 1: Add These line of code in your product page template, copy and past

<button type="submit" name="add" aria-label="Add to cart" class="btn product-form__cart-submit btn--secondary-accent ad_to_cart" id="ad_to_cart" aria-haspopup="dialog" data-add-to-cart="">

Step 2: Goto your assets directory and open it theme.js and past this below code

$(document).on('click','.ad_to_cart',function(){ 
var ID = $(this).find('.ad_to_cart_id').attr("var_id"); 
$.ajax({
type: 'POST',
url: '/cart/add.js',
data: {
  quantity: 1,
  id: $(this).find('.ad_to_cart_id').attr("var_id")
},
  dataType: 'json', 
 success: function (data) { 
  $('#CartCount span:first').text(data.quantity);
  console.log(data.quantity);
 
 } 
 });
}) 
like image 43
Aslam Khan Avatar answered Sep 27 '22 16:09

Aslam Khan