You have two options.
Option 1.
As cart JSON object doesn't provide information about variant inventory quantity available, you need to create such an object manually in the theme template. See the code below that will give you an idea how to get inventory quantity available for the items in your cart:
{%- assign cart_items_count = cart.items | size -%}
var cartItemMaxQuantities = {
{%- for item in cart.items -%}
"{{ item.id }}": {{- item.variant.inventory_quantity -}}
{%- unless forloop.index == cart_items_count -%},{%- endunless -%}
{%- endfor -%}
};
This will create a JSON object that you can use in your JS logic on adjusting cart items quantity. The object would look like that:
{
variant_id_1: max_available_quantity,
variant_id_2: max_available_quantity,
...,
variant_id_x: max_available_quantity
}
If you need to get updated object on adding/removing cart items using AJAX - create a new page template e.g. page.max-qtys.liquid
to output this JSON object. Then on adding/removing items, you can get the updated object by requesting any page on your website and adding a ?view=max-qtys
query param e.g. /pages/about?view=max-qtys
. Don't forget to add {% layout none %}
at the beginning of the template file to prevent load your site layout file and just output the object JSON. Below is the code for the page template.
{%- layout none -%}
{%- assign cart_items_count = cart.items | size -%}
{
{%- for item in cart.items -%}
"{{ item.id }}": {{- item.variant.inventory_quantity -}}
{%- unless forloop.index == cart_items_count -%},{%- endunless -%}
{%- endfor -%}
}
Option 2
Use /cart/add.json
on adding new items to the cart instead of /cart.update.json
or /cart/change.json
. Shopify will respond with 422 status code and won't allow you to add more items than available if you use /cart/add.json
endpoint.