Ad

Shopify Not Succeeding On All Jquery POST

- 1 answer

I have a cookie on my Shopify site that stores variant IDs that will be added to the cart on page load:

var mmuUserCart = [
  '10672503748',
  '10672622148'
];

$.cookie('mmu-cart', mmuUserCart, {expires: 10});

function readCookie(handle) {
  var cookieData = $.cookie(handle);
  cookieData = cookieData.split(',');

  if (cookieData) {
    if (cookieData.length > 0) {
      for (i = 0; i < cookieData.length; i++) { 
        console.log(cookieData[i]);

        jQuery.post('/cart/add.js', {
          quantity: 1,
          id: cookieData[i]
        });

        //           .fail( function(xhr, textStatus, errorThrown) {
        //               console.log(textStatus);
        //           });
      }
    }
  }
}

$(document).ready(function() {
  readCookie('mmu-cart');
});

But it only posts one of the items (randomly) and sometimes it posts both. But that's a 1/20 chance it adds both to the cart. No error message. Both items have plenty of stock. Is there a post limit on Shopify?

Ad

Answer

jQuery.post is asynch so you need to wait for the first post to return before posting the next variant. e.g.:

var mmuUserCart = [
  '10672503748',
  '10672622148'
];

$.cookie('mmu-cart', mmuUserCart, {expires: 10});

function readCookie(handle) {
  var cookieData = $.cookie(handle);
  cookieData = cookieData.split(',');

  if (cookieData) {
      function postVariant(){
        if(!cookieData.length) {
          //update any displayed cart ?;
          return;
        }
        var variantId = cookieData.shift();
        console.log(variantId);

        $.post('/cart/add.js', {
          quantity: 1,
          id: variantId
        }).done(postVariant);

      }
      postVariant();

    }
}

$(document).ready(function() {
  readCookie('mmu-cart');
});    
Ad
source: stackoverflow.com
Ad