$.fn.onAddToCartButtonClick = function(getDataCallback, productId, quantityInput){ $(this).click(function(event){ var data = getDataCallback(); let quantity = quantityInput.val(); addToCartProduct(productId, quantity, data.url, data.messages, data.customerEnteredPrice, data.selectedAttributes); }) } function addToCartProduct(productId, quantity, url, messages, customerEnteredPrice, selectedAttributes, giftCardAttributes) { $.ajax({ cache: false, type: "POST", contentType: "application/json; charset=utf-8", url: url, data: getAddToBasketRequestJson(productId, quantity, customerEnteredPrice, selectedAttributes, giftCardAttributes), success: function (data) { if (data.IsSuccess) { if(data.RedirectOnAddToCartUrl) { setLocation(data.RedirectOnAddToCartUrl); }else{ var durationMs = 3000; window.cfVue.toast.success(messages.success, durationMs, { override: true }); $(".cf_headerlinks_shoppngcart__counter span").html(data.TotalBasketQuantity); $(".current-basket-quantity span").html(data.TotalBasketQuantity); } } else if (data.Items) { const productsWithErrors = data.Items .filter(it => it.Errors?.length > 0) .filter(it => !it.IsSuccess); const errorMessages = productsWithErrors .map(it => it.Name + ":" + it.Errors.join(',')); window.cfVue.toast.error(String.format(messages.failed, errorMessages.join(';')), 10000, { override: true }); } else if (data && typeof data === "string"){ window.cfVue.toast.error(String.format(messages.failed, data), 10000, { override: true }); } }, error: function (er) { window.cfVue.toast.error(messages.failed, 10000, { override: true }); } }); } const getAddToBasketRequestJson = (productId, quantity, customerEnteredPrice, selectedAttributes, giftCardAttributes) => { var obj = { Items: [ { ProductId: productId, Quantity: quantity, CustomerEnteredPrice: customerEnteredPrice, SelectedAttributesJson: selectedAttributes, GiftCardAttributes: giftCardAttributes, } ] } return JSON.stringify(obj); }