I've modified the css in the launch theme to display the number of items in the cart header icon.
However, when I click the "add to cart" button the number does not update unless I refresh the page.
I'm new to developing on Shopify and would really appreciate some assistance.
Site:
password: LA2020#
Solved! Go to the solution
This is an accepted solution.
The product is being added to cart correctly, you will need to use JavaScript within the cart ajax call. I can see from the network tab that you are calling /cart.js, however you need to deal with the returned data to alter the cart count.
Within your ajax call to the cart end point, you need something along the lines of:
$.ajax(
//current options for your ajax add to cart
success: function(data){
var current_count = data.item_count;
$('.header-cart-count').html(current_count);
}
)
Thanks!
I was able to get the header cart icon updating when changing qty's on the cart page. However, when I update the cart via he product pages "Add to Cart" button the qty does not change.
Here is the cart function with the updated code in the _updateItem function. Does the product page add to cart button use this code or should I look somewhere else?
var StaticCart_StaticCart = /*#__PURE__*/function () {
function StaticCart(section) {
var _this = this;
StaticCart_classCallCheck(this, StaticCart);
this.$el = jquery_default()(section.el);
this.events = [jquery_default()('.cart-instructions textarea', this.$el).on('change.cart', function () {
return _this.saveSpecialInstructions();
}), jquery_default()('.dismiss', this.$el).on('click.cart', function () {
return _this.closeModal();
}), jquery_default()('.cart-modal-wrapper.active', this.$el).on('click.cart', function () {
return _this.closeModal();
}), jquery_default()('[data-calculate-shipping-button]', this.$el).on('click.cart', function () {
return _this.calculateShipping();
})];
this.cartForm = section.el.querySelector('[data-cart-form]');
if (this.cartForm) {
this.cartTable = this.cartForm.querySelector('[data-cart-table]');
this.cartDiscounts = this.cartForm.querySelector('[data-cart-discounts]');
this.totalPrice = this.cartForm.querySelector('[data-cart-subtotal]');
this._handleClick = this._handleClick.bind(this);
this._handleQtyChange = this._handleQtyChange.bind(this);
this._handleQtyKeydown = this._handleQtyKeydown.bind(this);
this.cartForm.addEventListener('click', this._handleClick);
this.cartForm.addEventListener('change', this._handleQtyChange);
this.cartForm.addEventListener('keydown', this._handleQtyKeydown);
this.updateTimeout = null;
}
this.context = {};
this.context.cart = JSON.parse(jquery_default()('[data-cart-strings]').text());
this.context.shipping = null;
this.$body = jquery_default()(document.body);
this.$modalWrapper = jquery_default()('.cart-modal-wrapper', this.$el);
this.$modalTitle = jquery_default()('[data-modal-title]', this.$el);
this.$modalMessage = jquery_default()('[data-modal-message]', this.$el);
this.$modalAction = jquery_default()('[data-modal-action]', this.$el);
this.$shippingCalculator = jquery_default()('[data-shipping-calculator]');
if (this.$shippingCalculator.length !== 0) {
try {
this.context.shipping = JSON.parse(jquery_default()('[data-shipping-calculator-strings]').text());
} catch (error) {
console.log('No shipping localisations found, unable to continue.');
}
if (this.context.shipping == null) {
return;
}
if (this.context.shipping.customerCountry) {
this.calculateShipping();
}
if (jquery_default()('.cart-items').length) {
this.shippingCalculator();
}
}
Shopify.onError = function (XMLHttpRequest) {
_this.handleErrors(XMLHttpRequest);
};
}
StaticCart_createClass(StaticCart, [{
key: "saveSpecialInstructions",
value: function saveSpecialInstructions() {
var newNote = jquery_default()('.cart-instructions textarea').val();
Shopify.updateCartNote(newNote, function (cart) {// empty function so that Shopify's callback isn't invoked
});
}
/**
* Gets the current value of the quantity input box for a given line item key
*
* {string} key
*/
}, {
key: "_getItemQuantity",
value: function _getItemQuantity(key) {
return parseInt(this.cartForm.querySelector("[data-cart-item-key=\"".concat(key, "\"] [data-cart-product-quantity]")).value, 10);
}
/**
* Sets a value for the quantity input box for a given line item key
*
* {string} key
*
* {integer} quantity
*/
}, {
key: "_setItemQuantity",
value: function _setItemQuantity(key, quantity) {
this.cartForm.querySelector("[data-cart-item-key=\"".concat(key, "\"] [data-cart-product-quantity]")).value = quantity;
}
}, {
key: "_handleClick",
value: function _handleClick(event) {
if (!event.target.hasAttribute('data-cart-action')) {
return;
}
var cartAction = event.target.dataset.cartAction;
var key = _getItemKey(event.target);
var oldQuantity = this._getItemQuantity(key);
var newQuantity;
switch (cartAction) {
case 'increment':
newQuantity = oldQuantity + 1;
this._setItemQuantity(key, newQuantity);
this._updateItem(key, newQuantity);
break;
case 'decrement':
newQuantity = Math.max(oldQuantity - 1, 0);
this._setItemQuantity(key, newQuantity);
this._updateItem(key, newQuantity);
break;
case 'remove':
event.preventDefault();
this._setItemQuantity(key, 0);
this._updateItem(key, 0);
break;
default:
// do nothing
break;
}
}
}, {
key: "_handleQtyChange",
value: function _handleQtyChange(event) {
if (!event.target.hasAttribute('data-cart-product-quantity')) {
return;
}
var key = _getItemKey(event.target);
var quantity = this._getItemQuantity(key);
this._updateItem(key, quantity);
}
}, {
key: "_handleQtyKeydown",
value: function _handleQtyKeydown(event) {
if (event.target.hasAttribute('data-cart-product-quantity') && event.key === 'Enter') {
event.preventDefault();
this._handleQtyChange(event);
}
}
/**
* Sends a request to the server to update a single product
*
* {string} key Shopify line item key (or product ID)
*
* {integer} quantity New quantity for item. If 0, item will be removed from cart.
* @private
*/
}, {
key: "_updateItem",
value: function _updateItem(key, quantity) {
var _this2 = this;
// cancel any pending requests
if (this.updateTimeout !== null) {
clearTimeout(this.updateTimeout);
}
this.updateTimeout = setTimeout(function () {
if (_this2._getItemQuantity(key) !== quantity) {
_this2.updateTimeout = null;
return;
}
var thisTimeoutId = _this2.updateTimeout;
jquery_default.a.ajax({
type: 'POST',
url: "".concat(window.Theme.routes.cart_change_url, ".js"),
dataType: 'json',
data: {
quantity: quantity,
id: key
},
success: function success(cart) {
if (_this2.updateTimeout !== thisTimeoutId) {
return;
}
if (cart.item_count === 0) {
// reload to show empty cart state
window.location.reload();
return;
}
_this2._updateCart(thisTimeoutId);
/*fix to update cart icon with new qty for cart page */
var current_count = cart.item_count;
$('.header-cart-count').html(current_count);
}
});
}, 300);
}
/**
* _updateCart
*
* Fetches new cart contents and swaps into page
*
* {integer} thisTimeoutId Id of timeout for this request. If no longer current, update is cancelled.
*/
}, {
key: "_updateCart",
value: function _updateCart(thisTimeoutId) {
var _this3 = this;
shopify_asyncview_dist_index_es.load(window.Theme.routes.cart_url, '_ajax').done(function (_ref) {
var options = _ref.options,
html = _ref.html;
// If another request is in progress, discard this update
if (_this3.updateTimeout !== thisTimeoutId) {
return;
} // Inject new cart table contents
var newTableContainer = document.createElement('div');
newTableContainer.innerHTML = html.table;
morphdom_esm(_this3.cartTable, newTableContainer.querySelector('table'), {
onBeforeElUpdated: function onBeforeElUpdated(fromEl, toEl) {
// Skip images if src matches
// - we don't want to reload lazy loaded images
if (fromEl.tagName === 'IMG' && fromEl.src=== toEl.src) {
return false;
}
return true;
}
});
dist_index_es.watch(_this3.cartTable); // Inject new cart level discounts
_this3.cartDiscounts.innerHTML = html.discounts; // Update total
_this3.totalPrice.innerHTML = options.totalPrice;
}).fail(function () {
return window.location.reload();
});
}
}, {
key: "shippingCalculator",
value: function shippingCalculator() {
var _this4 = this;
Shopify.Cart.ShippingCalculator.show({
submitButton: this.context.shipping.submitButton,
submitButtonDisabled: this.context.shipping.submitButtonProcessing,
customerIsLoggedIn: this.context.shipping.customerCountry,
moneyFormat: Theme.moneyFormat
});
var selectableOptions = this.$shippingCalculator.find('select');
setTimeout(function () {
selectableOptions.map(function (select) {
return _this4.updateShippingLabel(select);
});
}, 500);
jquery_default()('.cart-shipping-calculator select').change(function () {
selectableOptions.map(function (select) {
return _this4.updateShippingLabel(select);
});
});
}
}, {
key: "calculateShipping",
value: function calculateShipping() {
var _this5 = this;
jquery_default()('[data-calculate-shipping-button]').val(this.context.shipping.submitButtonProcessing);
var shippingAddress = {};
shippingAddress.zip = jquery_default()('.address-zip').val() || '';
shippingAddress.country = jquery_default()('.address-country').val() || '';
shippingAddress.province = jquery_default()('.address-province').val() || '';
var queryString = Object.keys(shippingAddress).map(function (key) {
return "".concat(encodeURIComponent("shipping_address[".concat(key, "]")), "=").concat(encodeURIComponent(shippingAddress[key]));
}).join('&');
jquery_default.a.ajax("".concat(window.Theme.routes.cart_url, "/shipping_rates.json?").concat(queryString), {
dataType: 'json'
}).fail(function (error) {
return _this5.handleErrors(error.responseJSON || {});
}).done(function (response) {
var rates = response.shipping_rates;
var address;
var responseText;
if (shippingAddress.zip.length) {
address = shippingAddress.zip;
}
if (shippingAddress.province.length) {
address = "".concat(address, ", ").concat(shippingAddress.province);
}
if (shippingAddress.country.length) {
address = "".concat(address, ", ").concat(shippingAddress.country);
}
var shippingCalculatorResponse = jquery_default()('.cart-shipping-calculator-response');
shippingCalculatorResponse.empty().append("<p class='shipping-calculator-response message'/><ul class='shipping-rates'/>");
var ratesFeedback = jquery_default()('.shipping-calculator-response');
if (rates.length > 1) {
var firstRate = Shopify.Cart.ShippingCalculator.formatRate(rates[0].price);
responseText = _this5.context.shipping.multiRates.replace('** address **', address).replace('** number_of_rates **', rates.length).replace('** rate **', "<span class='money'>".concat(firstRate, "</span>"));
ratesFeedback.html(responseText);
} else if (rates.length === 1) {
responseText = _this5.context.shipping.oneRate.replace('** address **', address);
ratesFeedback.html(responseText);
} else {
ratesFeedback.html(_this5.context.shipping.noRates);
}
rates.forEach(function (rate) {
var price = Shopify.Cart.ShippingCalculator.formatRate(rate.price);
var rateValues = _this5.context.shipping.rateValues.replace('** rate_title **', rate.name).replace('** rate **', "<span class='money'>".concat(price, "</span>"));
jquery_default()('.shipping-rates').append("<li>".concat(rateValues, "</li>"));
});
jquery_default()('[data-calculate-shipping-button]').val(_this5.context.shipping.submitButton);
});
}
}, {
key: "updateShippingLabel",
value: function updateShippingLabel(value) {
var _this6 = this;
if (value) {
var select = jquery_default()(value);
var selectedOption = select.find('option:selected').val();
if (!selectedOption) {
selectedOption = select.prev('.selected-text').data('default');
}
select.prev('.selected-text').text(selectedOption);
setTimeout(function () {
if (select.attr('name') === 'address[country]') {
_this6.updateShippingLabel(jquery_default()('#address_province'));
}
}, 500);
}
}
}, {
key: "openModal",
value: function openModal(title, message, action) {
this.$modalTitle.text(title);
this.$modalMessage.text(message);
this.$modalAction.text(action);
this.$modalWrapper.addClass('active');
}
}, {
key: "closeModal",
value: function closeModal() {
this.$modalWrapper.removeClass('active');
this.$modalTitle.text('');
this.$modalMessage.text('');
this.$modalAction.text('');
}
}, {
key: "handleErrors",
value: function handleErrors(errorMessage) {
if (errorMessage.zip || errorMessage.country) {
var errorText = '';
if (errorMessage.country) {
errorText += "".concat(this.context.shipping.countryErrorMessage.replace('** error_message **', errorMessage.country), "<br/>");
}
if (errorMessage.zip) {
errorText += this.context.shipping.zipErrorMessage.replace('** error_message **', errorMessage.zip);
}
jquery_default()('.cart-shipping-calculator-response').html("<p>".concat(errorText, "</p>"));
} else {
console.log('Error', errorMessage.stringify());
}
}
}, {
key: "onSectionUnload",
value: function onSectionUnload() {
this.events.forEach(function ($el) {
return $el.off('.cart');
});
if (this.cartForm) {
this.cartForm.removeEventListener('click', this._handleClick);
this.cartForm.removeEventListener('change', this._handleQtyChange);
this.cartForm.removeEventListener('keydown', this._handleQtyKeydown);
}
}
}]);
return StaticCart;
}();
That's great news mate!!
Happy coding
User | Count |
---|---|
24 | |
20 | |
17 | |
16 | |
15 |