简体   繁体   中英

cart data not update in shopify using ajax

I have a Problem in Shopify.

I want update cart quantity on button click using ajax but it will give error like

{"status":404,"message":"Cart Error","description":"Cannot find variant"}

Here is my ajax code,

 $('.adjust-plus').click(function(){
    var qty = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').val();
    var varient = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').attr('data-id');

    jQuery.ajax({
      type: 'POST',
      async: false,
      url: '/cart/update.js',
      data: { updates: { varient : qty } },
      dataType: 'json',
      success: function() { location.href = '/cart'; }
   });
 });

currently in both variable value come so no any error in value.

but when id add code like:

$('.adjust-plus').click(function(){
    var qty = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').val();
    var varient = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').attr('data-id');

    jQuery.ajax({
      type: 'POST',
      async: false,
      url: '/cart/update.js',
      data: { updates: { 15082896588867 : 2 } },
      dataType: 'json',
      success: function() { location.href = '/cart'; }
   });
 });

then cart updated successfully.

Firstly, remove async: false as it's very bad practice and not needed here as you're using the success callback properly.

The issue itself is because you cannot use variables as the keys of an object with the syntax you're using. To get around this you can use bracket notation, like this:

$('.adjust-plus').click(function() {
  var $quantity = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity');
  var qty = $quantity.val();
  var varient = $quantity.data('id');

  var data = { updates: {} };
  data.updates[varient] = qty;

  jQuery.ajax({
    type: 'POST',
    url: '/cart/update.js',
    data: data,
    dataType: 'json',
    success: function() { 
      location.href = '/cart'; 
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM