After analyzing the values required from product.json, I realized that the current method is not efficient. The client-side ends up processing unnecessary information and every new product or option adds to the request load. Below is the script responsible for this process:
var CompareTotal = 0;
$.each(cart.items, function(index, cartItem) {
var varID = cartItem.variant_id;
var comparePrice= '';
var TotalcomparePrice = '';
$.ajax({
url: '/products/' + cartItem.handle + '.js',
dataType: 'json',
async: false,
success: function(product){
product.variants.forEach(function(variant) {
if ( variant.id == varID && variant.compare_at_price !== 0){
comparePrice = variant.compare_at_price;
TotalcomparePrice = cartItem.quantity * comparePrice;
CompareTotal = CompareTotal + TotalcomparePrice;
return false;
}
});
}
});});
To optimize these processes and enhance speed, I implemented an alternative cart template containing all necessary values. Now, the goal is to retrieve these values by replacing the previous approach. However, using dataType: 'JSON' is not possible as the default data comes from the server-side. Here is a glimpse of the alternative template:
{ "token": "eacf539f884b717a2a74ac775b9b8923", "note": "", "attributes": {}, "original_total_price": 2390, "total_price": 2390, "total_discount": 0, "total_weight": 0.0, "item_count": 2, "items": [{ "id": 31286186180719, "properties": { }, "quantity": 2, "variant_id": 31286186180719, "key": "31286186180719:404d70730b155abbf5e62b28445537ae", "title": "RO - 1. Darkest Brown \u0026 Dark Auburn Mix", "compare_at_price": 1595, "compare_line_price": 3190, "price": 1195, "original_price": 1195, "discounted_price...
I have successfully fetched all necessary information via console log after setting up the request. Here's how it was done:
$.ajax({
type: 'GET',
url: '/cart?view=data',
success: function(response) {
json_response = JSON.parse(response);
console.log( 'response', json_response );
},
error: function(status) {
console.warn( 'ERROR', status );
}});
The next step involves extracting the values of compare_line_price for each product and total_compare_price for the entire cart. With handlebars, I can then display them. As a self-taught individual, each progression in this aspect presents challenges. Any guidance on the way forward would be greatly appreciated.
{%- layout none -%}
{%- assign cartJson = cart | json -%}
{%- assign cartToken = cartJson | split:'token":"' | last | split:'"' | first | json -%}
{% assign total_cart_compare_price = 0 %}
{
"token": {{ cartToken }},
"note": {{ cart.note | json }},
"attributes": {{ cart.attributes | json }},
"original_total_price": {{ cart.original_total_price | json }},
"total_price": {{ cart.total_price | json }},
"total_discount": {{ cart.total_discount | json }},
"total_weight": {{ cart.total_weight | json }},
...
Here's a preview of the alternative cart template.