Error when using new Ajax API

Solved
Highlighted
Shopify Partner
39 1 12

I'm attempting to add multiple products to cart using the new Ajax API but I'm running into this error message:

{"status":"bad_request","message":"Parameter Missing or Invalid","description":"Required parameter missing or invalid: items"}

My JavaScript is as follows:

$(document).on('click', '.ajax-submit', function (e) {
  e.preventDefault();
  var $primaryProduct = $(this).data('product');
  var productsToAdd = [];
  var items = [];
  var item = {};
  var handle;
  productsToAdd.push($primaryProduct);

  $('.companion-product input[type="checkbox"]:checked').each(function () {
    handle = $(this).data('product');
    productsToAdd.push(handle);
  });

  $.ajax({
    type: 'POST',
    url: '/cart/add.js',
    data: items,
    dataType: 'json',
    beforeSend: function () {
      console.log('beforeSend');

      for (var i = 0; i < productsToAdd.length; i++) {
        items.push({
          quantity: 1,
          id: productsToAdd[i]
        });
      };

      console.log(items);
    },
    success: function (itemData) {
      console.log('success');
    },
    error: function (XMLHttpRequest) {
      console.log(XMLHttpRequest.responseText);
    }
  });

  return false;
});

A console log of items, shows as follows
image.png

Liam Merlyn | Shopify Developer
0 Likes
Highlighted
Shopify Staff
Shopify Staff
1041 140 165

This is an accepted solution.

Hey @ConduciveMammal 

 

data should point to an object with an 'items' key.

 

Try changing data: items to data: { items: items }

 

0 Likes
Highlighted
Shopify Partner
39 1 12

Ahh amazing, Scotty! Thanks so much!

Liam Merlyn | Shopify Developer
0 Likes