Adding multiple variants to cart using items array

OwenLD
Tourist
6 0 2

When adding items to the cart the docs mention that 'You can add multiple variants to the cart by appending more objects in the items array'. (https://help.shopify.com/en/themes/development/getting-started/using-ajax-api#add-to-cart)

 

This does not seem to work for me, even with one item in the array like they are using in their example.

 

I can get one item to add by changing the data to this:

{
    quantity: 1,
    id: 20665810092102
}

However, when the data is changed to this:

{
    items: [
        {
            quantity: 1,
            id: 20665810092102
        }
    ]
}

I then get an error. The error I am getting is in the console is '[shop_events_listener] Error in handleXhrDone: e.id is undefined'. Has anyone managed to get this working?

Replies 16 (16)
SBD_
Shopify Staff
Shopify Staff
1098 146 227

Hey @OwenLD,

 

It's working for me - I get a warning after it completes, but the items are added to cart. The warning appears to be from the analytics code, but it shouldn't affect the add to cart. Have you checked cart afterwards? It could also be caused by some custom JS in the theme - can you provide the shop URL (reply or DM)?

Scott | Developer Support @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

OwenLD
Tourist
6 0 2

Hi @SBD_. Thanks for the reply.

 

After looking at this again it seems that I was setting the wrong content-type on my request.

 

My request now looks like this:

const data = {
	items: [
		{
			quantity: 1,
			id: variantid1
		},
		{
			quantity: 2,
			id: variantid2
		}
	]
};

const xhr = new XMLHttpRequest();
xhr.open('POST', '/cart/add.js', true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.send(JSON.stringify(data));

This now works as expected.

OwenLD
Tourist
6 0 2

Hi @SBD_,

 

I am now trying to get error reporting working on the ajax cart. When the user adds more quantity to the cart than is in stock, I want to return an erorr.

 

For example if there is a variant with 10 stock, I don't want the user to be able to add more than 10.

 

The response status is 200 even when the user adds more than are in stock, is this expected?

 

The only way I have managed to get this working so far is by adding the items one by one to the cart and queueing the ajax calls. This is not ideal as it takes longer than adding all the items in one ajax call.

 

Is there a way I can get the error messaging with one ajax call for multiple items?

 

EDIT: The following is required on the request to get error reporting working:

xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

Maybe this should be added to the docs as not everyone uses jQuery? Could save people a lot of time.

SBD_
Shopify Staff
Shopify Staff
1098 146 227

Hey @OwenLD,

 

You should hit a 422: 

 

{"status":422,"message":"Cart Error","description":"You can't add more ... to the cart."}

Is the product configured to oversell? Can you share a link to the product page (in reply or DM)?

 

Also, the variant.inventory_quantity might be handy here too (for client-side validation).

Scott | Developer Support @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

SBD_
Shopify Staff
Shopify Staff
1098 146 227

Ah sorry missed the last part of your reply, so it works when you set a X-Requested-With header? Interesting, I'll dig deeper. Are you able to share a demo page or some vanilla JS examples?

Scott | Developer Support @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

OwenLD
Tourist
6 0 2

Hi @SBD_,

 

When I was testing, the request would always return a 200 without a X-Requested-With header. Regardless of what you are adding to the cart.

 

This is what my request looks like:

function request(success) {
	const xhr = new XMLHttpRequest();
	xhr.open('POST', '/cart/add.js', true);
	xhr.onreadystatechange = () => {
		if (xhr.readyState > 3) success(xhr);
	};
	xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
	xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
	xhr.send(JSON.stringify({items: items}));
}

Where 'items' is an array of selected variants.

SBD_
Shopify Staff
Shopify Staff
1098 146 227

I'm able to replicate. This is being discussed internally. Thanks for reporting.

Scott | Developer Support @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

SBD_
Shopify Staff
Shopify Staff
1098 146 227

Hey @OwenLD,

 

This has been resolved, the response should now be consistent.

Scott | Developer Support @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

dscnex
Tourist
4 0 0

Hi, I'm having the same problem. I don't receive any error in the console, but the script in "shop_events_list..." that is waiting for the call to cart/add.js is failing to parse the response and because of that, pushing an undefined product to enhanced ecommerce (G. analytics).

This also generates problem on our G. Analytics reports

dscnex
Tourist
4 0 0
SBD_
Shopify Staff
Shopify Staff
1098 146 227

Hey @dscnex,

 

Are the items added to cart? If not, can you provide a snippet of the code?

 

 

Scott | Developer Support @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

dscnex
Tourist
4 0 0

They are added. The only problem is that the response from this ajax call is not processed correctly, so the event listeners don't know what products have just been added

kjdointhings
Excursionist
21 1 10

Same issue. Products are being added to cart but there is no response to the success callback.

SBD_
Shopify Staff
Shopify Staff
1098 146 227

Hey @kjdointhings,

 

Can you please provide a code sample / example store url?

Scott | Developer Support @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

kjdointhings
Excursionist
21 1 10

The following will add the items to cart but the success callback does not fire:

    var items = [
      { quantity: 1, id: 28615271105 },
      { quantity: 1, id: 37548776065 }
    ];

    $.ajax({
      type: "POST",
      url: '/cart/add.js',
      data: { items: items },
      success: function(data) {
        console.info('success',data);
      },
      dataType: 'application/json'
    });

And this will add the items to cart, the error callback will fire, then the .always callback will fire and return the added items. Can this be addressed so the success callback fires as expected?

 

    var items = [
      { quantity: 1, id: 28615271105 },
      { quantity: 1, id: 37548776065 }
    ];

    $.post('/cart/add.js', {
      items: items
    })
    .done(function() {
      console.log( "success" );
    })
    .fail(function() {
      console.log( "error" );
    })
    .always(function(data) {
      console.info('finished',JSON.parse(data.responseText));
    });
SBD_
Shopify Staff
Shopify Staff
1098 146 227

Hey @kjdointhings,

 

Those method are expecting the response to have a `application/json` content-type, so jQuery's failure callback fires.

 

Post to /cart/add.json instead.

 

 

 

Scott | Developer Support @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog