AJAX re-rendering of the cart after custom cart requests
Asked Answered
P

1

1

I'm building a Shopify app which offers additional products or services related to some identified products. In some cases, I end up adding a product to cart from cart page.

I found this question quite useful, to take actions on cart changes. The issue is that I'm currently forced to reload the page to re-render the cart along with the new product. I can't reasonably reconstruct the cart myself to include new items.

Hence, is there a way to trigger an "AJAX rendering" of the cart and avoid a full page reload ?

Poisonous answered 20/8, 2020 at 17:17 Comment(0)
N
2

You can achieve this in many ways depending on your end goal. From your description, I have understood that you just want your script to run on Cart page. However, just note that a user may proceed to Checkout page without visiting Cart page. So just cover all your use cases.

This would have been much easier if you had to do this in theme and not in an app. Since, your app does not have any idea about the markup of Cart page, it is not easy to just append the new product row to existing table. As a workaround, on adding new product, call the cart page via Ajax, parse the returned HTML and replace the Cart form. So after adding new product, just call the below code to re render product form on Cart page.

function RerenderCart() {
  $.get("/cart", function (data) {
    const parser = new DOMParser();
    const doc = parser.parseFromString(data, "text/html");
    const formSelector = doc.querySelector("form[action='/cart']");
    $("form[action='/cart']").replaceWith(formSelector);
  });
}

Add checks for cart page and if form was found in returned HTML.

This code works fine on Debut Shopify theme. Just thoroughly test it on all your use cases.

DOMParser

Notogaea answered 21/8, 2020 at 9:48 Comment(1)
Do you have any idea why this DOMParser might not be displaying svg icons sometimesPothunter

© 2022 - 2024 — McMap. All rights reserved.