Hello Shopify community,
I’m currently working on developing an app that offers upsell functionality, allowing users to add items to their cart with discounts and free shipping. However, I’m facing an issue with applying the correct discount to the added items.
I’ve tried various methods using the AJAX API to add items to the cart, but unfortunately, the discounts are not being applied as intended. What I want is to add an item to the cart and have only that specific item receive the discount that was applied during the addition process.
I’ve spent considerable time researching and trying different approaches, but none have yielded the desired results. I’ve looked through multiple resources and attempted several possible workarounds, but they haven’t worked as expected.
If anyone has experience with a similar issue or has insights into the proper way to apply discounts through the AJAX API when adding items to the cart, I would greatly appreciate your assistance
Try:1
This way it add item to cart but it removes the previous items from cart.
let productId = 41172450050199;
let quantity = 1;
let discountCode = 'MY_CODE_23';
let productUrl = `/cart/${productId}:${quantity}?discount=${discountCode}`;
$.ajax({
type: 'POST',
url: productUrl,
dataType: 'json',
async: false,
success: function (res) {
console.log("Item added to cart. ", res);
},
error: function (res) {
console.log("Error while adding item to cart. ", res);
}
});
Here MY_CODE_23 is created in Discount
Try:2
This way it adds item to cart but also adds the same discount for all available items in cart considering even if some item should not have discount.
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
async: false,
data: {
items: [
{
id: 41172449558999,
quantity: 1,
properties: {},
}
],
},
success: function (res) {
console.log("item added to cart. ", res);
applyDiscountCode(res.variant_id, 'MY_CODE_23');
},
error: function (res) {
console.log("Error while adding item to cart. ", res);
}
});
function applyDiscountCode(variantId, discountCode) {
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
async: false,
data: {
id: variantId,
quantity: 1,
properties: {},
discount_code: discountCode,
},
success: function (res) {
console.log("Discount code applied. ", res);
},
error: function (res) {
console.log("Error while applying discount code. ", res);
}
});
}
Here it add item into cart with discount but it throws error like: Required parameter missing or invalid: items
I’ve explored various other methods, but unfortunately, none of them have provided a valid solution. As time is of the essence, I need to complete this task as soon as possible. If anyone has any insights or suggestions that could be helpful in resolving this issue, I would be immensely grateful for your help.
Thank you for taking the time to read my post and for sharing your expertise!


