How to Update cart.note in side of checkout.liquid

Highlighted
New Member
1 0 1

I have a Shopify Plus account. Inside of the checkout.liquid file I have this snippet that captures the gift message in the checkout page: 

 

<div class="cart-notes-form"> 
<textarea class="cart-notes-textarea{% if checkout.note != blank %} disabled{% endif %}" placeholder="Enter gift note here." value="{{checkout.note}}" name="checkout[note]" data-cart-notes-textarea maxlength="160">{{ checkout.note }}</textarea> <button class="cart-notes-submit" data-cart-notes-submit type="submit">Add Gift Message</button> <span class="cart-notes-textarea-counter" gift-note-character-counter> 0 / 160 remaining</span> </div>

 Here's the AJAX call to make a POST request to the /cart/update.js: 

      $('body').on('click', '[data-cart-notes-submit]', function (event) {
        var giftNoteMassage = $('[data-cart-notes-textarea]').val();
        event.preventDefault();
        
        saveCartNote(this);

        if (giftNoteMassage.length > 0) {
          updateGiftNotes(giftNoteMassage)
        }  
      });
  function updateGiftNotes(note) {
    $.ajax({
      url: '/cart/update.js',
      method: 'POST',
      data: {note: note},
      success: function(result) { 
        // page refresh needed after POST request or note update won't persist in /cart/update.js
        window.location.href=window.location.href
        return result;
      },
      error: function(jqxhr, status, exception) {
          console.log(exception);
      }
    }); 
  }

 

So this is working. but I noticed that when the page has to refresh after the AJAX call or the cart.note won't be updated (in the snippet above I used window.location.href=window.location.href to refresh the page).

Is there a way that I could update the cart.note from within the checkout page without refreshing? This is ideal because I've noticed that the input fields in the address form will be cleared out after the page refresh, and it's not a good user experience. Any suggestion or alternative solution is appreciated. 

 

1 Like
Highlighted
Shopify Expert
8 0 1

Bump! Would be good to know the answer to this.

Wondering if using this function would help, as it "... is triggered when the page is still the same, but sections have been “re-painted” (ie. the discount form is submitted)." (reference: https://shopify.dev/docs/themes/files/checkout-liquid)

 

$(document).on(`page:load page:change`, function() {
  // add content
});

 

0 Likes