jquery - How to update line item properties in shopify
I want to add custom info in line item properties using jQuery. Line item properties (https://help.shopify.com/en/themes/liquid/objects/line_item#line_item-properties) which i can update on click of a checkbox. I have tried this but it is not working
$.ajax({
url: "/cart/update.js",
type: "POST",
data: '{"updates":{ "1234567890": { "properties":{ "Someprop": "Somevalue" }}}}',
contentType: "application/json",
dataType: 'json'
}
});
Answer
Solution:
You're close!
Theupdate
endpoint can update multiple products at once, but cannot change the line-item properties.
You're looking for thechange
endpoint, which can modify a single line in greater detail.
$.ajax({
url: "/cart/change.js",
type: "POST",
data: '{"id":"1234567890", "quantity": 1, "properties":{ "Someprop": "Somevalue" } }',
contentType: "application/json",
dataType: 'json'
}
});
NOTE: The data must contain either "line" (1-based index of item's position in the cart.items array) or "id" (which can either be the item'sid
orkey
value). I recommend updating using theitem.key
for the ID field when using both the /change and the /update endpoints:id
is just the variant ID, and when using line-item properties the same ID can therefore be repeated across multiple lines. Thekey
is guaranteed to be unique.
Additionally, when hitting the /cart/change endpoint, if you do not specify the quantity parameter Shopify may default the line's quantity to 1. To be safe, I would recommend always explicitly passing the line's current quantity.
Note that Shopify will replace the line-item properties for the edited item with the line-item properties object that you supply. Per Corey's comment, the safest thing to do when updating a line item's properties is to get the existing properties for the line, update the value(s) that need updating, then hit the/cart/change.js
endpoint with the updated object.
Additionally, per Bart Coppens' observation in the comments, an empty properties object is ignored by Shopify. This makes deleting all properties from a line item a bit problematic. The best workaround I have been able to come up with so far is to use a placeholder value whose key begins with an underscore, as the leading underscore causes Shopify to hide the property on the Checkout. (For example, I might use_validated: true/false
). If your theme doesn't already hide properties with a leading underscore, find the properties loop (usually beginning withfor p in item.properties
) and add the following:
{% if p.first.first == '_' %} {% continue %} {% endif %}
Source
Didn't find the answer?
Our community is visited by hundreds of Shopify development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.