Exploring the capabilities of Ajax while enhancing shopping cart functionality

website: Upon adding a product to the cart, it will display the recently added product, total, and an option to proceed to the cart. I am looking to include a count of other items in the cart as well, such as: "There are currently 5 more products in the cart."

I attempted to use {{ cart.item_count }}, however, due to the Ajax functionality of the popup, it does not update in real-time, only showing the initial number of products in the cart (thus providing incorrect information).

How can I implement a solution for this problem? Below is a test based on answers from other sources that I tried, but unfortunately, it did not work.

<div class="loading-modal modal">{{ 'general.search.loading' | t }}</div> 

<div class="newsletter-success-modal">
  <div class="modal-overlay"></div>
  <div class="ajax-modal-content">
    <a class="close close-window btn" title="{{ 'general.password_page.close' | t }}">
      <i class="fa fa-times"></i>
    </a>
    <i class="fa fa-check" aria-hidden="true"></i>
    <span>{{ 'general.newsletter_form.mailing_list_success_message' | t }}</span>
  </div>
</div>  

<div class="ajax-error-modal modal">
  <div class="modal-inner">
    <div class="ajax-error-title">{{ 'general.search.error' | t }}</div>
    <div class="ajax-error-message"></div>
  </div>
</div>
<div class="ajax-success-modal modal">
    <div class="overlay"></div>
    <div class="content"> 
      
      
      <div class="ajax-left">    
        <p class="added-to-cart info">{{ 'cart.general.added_to_cart' | t }}</p>
      <p class="added-to-wishlist info">{{ 'products.wishlist.added_to_wishlist' | t }}</p>
      <img class="ajax-product-image" alt="modal window" src="/" />
       <div class="ajax-cart-desc">
        <h3 class="ajax-product-title"></h3>
        <span class="ajax_price"></span>
        <p>{{ 'cart.general.qty' | t }}:&nbsp;<span class="ajax_qty"></span></p>
        </div>
      </div>
      <div class="ajax-right"> 
      
        <div>Total in Cart: <span class="ajax_cartTotal"></span><br>
          <span class="cart-item-count"> </span>
        </div>
          <button class="btn continue-shopping" onclick="javascript:void(0)">{{ 'cart.general.continue_shopping' | t }}</button>
        <div class="success-message added-to-cart"><a href="/cart" class="btn"><i class="fa fa-shopping-cart"></i>{{ 'cart.general.view_cart' | t }}</a> </div>  
      
      </div>
    <a href="javascript:void(0)" class="close-modal"><i class="fa fa-times-circle"></i></a>
    </div>    
</div>
   <script type="text/javascript">
$(function(){
    var cartCount = {{ cart.item_count }};
    $('.varients-item').on('click', function(){
        var obj = $(this);
        $.ajax({
            type: 'POST',
            url: '/cart/add.js',
            data: {
                quantity: 1,
                id: $(this).attr("data-variant")
            },
            dataType: 'json',
            success: function (data) {
                $.ajax({
                    type: 'GET',
                    dataType: 'json',
                    url: '/cart.json',
                    success: function(cart){
                        cartCount++;
                        $('.cart-item-count').html(cartCount);
                    }
                });
            }
        });
    });
});

  </script>

Answer â„–1

To implement the necessary updates, your JavaScript code should closely resemble the demo code provided below:

$(function(){
    $('.varients-item').on('click', function(){
        var obj = $(this);
        $.ajax({
            type: 'POST',
            url: '/cart/add.js',
            data: {
                quantity: 1,
                id: $(this).attr("data-variant")
            },
            dataType: 'json',
            success: function (data) {
                $.ajax({
                    type: 'GET',
                    dataType: 'json',
                    url: '/cart.js',
                    success: function(cart){
                        // Update the cart item count based on the latest data received from the AJAX API
                        let total = cart.item_count;
                        $('.cart-item-count').html(total);
                    }
                });
            }
        });
    });
});

You can find more information about the cart.js script in the Shopify documentation. Link https://i.sstatic.net/EziOW.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The method WebKitBrowser.StringByEvaluatingJavaScriptFromString does not provide any output

After running all JavaScript, I need to retrieve the HTML content. However, I am facing an issue using WebKit.NET where the method WebKitBrowser.StringByEvaluatingJavaScriptFromString does not return anything, even with a simple alert(). When I try passi ...

Ensure the secure running of my PHP script when triggered from an AJAX request

Similar Question: how to secure ajaxRequest.open php script I am currently attempting to create an AJAX call from jQuery to a PHP script on my own server like so: $.ajax({ url: 'ajax.php', .... Is there a way to ensure that this file can on ...

Is it possible for my node.js to become unresponsive when comparing lists?

In my node.js app, I have two lists - one retrieved from a database and the other created by listing file names on a server. Both lists contain approximately 750,000 strings each, and now I need to search for each string in one list within the other. As a ...

Step-by-step guide on transferring an HTML5 sqlite result set to a server using AJAX

Imagine I have a scenario where I receive a result set as shown below: db.transaction( function(transaction) { transaction.executeSql( 'SELECT col1, col2, col3 FROM table;', [],function(transaction, result){ //need to find a ...

Element sticking on scroll down and sticking on scroll up movements

I am currently working on a sticky sidebar that catches and stays fixed at a certain scroll point using JavaScript. However, I am facing an issue where I need the sidebar to catch when scrolling back up and not go further than its initial starting point. ...

Tips for navigating the HTML DOM without using window.scrollBy(x, y) (specifically for scrolling within an element)

Desiring to scroll down along with my selected document, I experimented with the following code. window.scrollTo(x, y); const body = document.getElementsByClassName("body")[0]; body.scrollTo(x, y); However, there are instances where it returns "undefined ...

Locate and substitute text, language equivalency

I'm encountering issues with finding and replacing words in PHP files, especially when dealing with a large number of them. I'm considering using javascript/jQuery as an alternative solution. I want to create a table mapping word_to_replace to ne ...

How can I execute JavaScript within a for loop in the server-side code?

protected void Button1_Click(object sender, EventArgs e) { for (int i = 0; i < 100; i++) { Page.ClientScript.RegisterClientScriptBlock(GetType(), "myScript", "<script>alert('hello world');</script>"); } } Is th ...

A JavaScript function that fetches the color name based on either the RGB value or the Hexadecimal value

Looking for a JavaScript function that can determine the name of a color. Would like the JavaScript function to be structured as shown below: function getColorName(r, g, b) { .... return <color name>; // such as blue, cyan, magenta, etc. } ...

What is the best way to incorporate a mongoose model into another model?

I have two different models that I am working with. In the user model, I want to include an array of Requests, and in the Request Model, I want to have User as an attribute (without including the password). How can I achieve this? var userSchema = new S ...

"An ExceptionInInitializer error occurred - Can you provide more details,

An Issue Has Arisen: Exception in thread "main" java.lang.ExceptionInInitializerError at com.PoseidonTechnologies.caveworld.level.WoRe.<init>(WoRe.java:46) at com.PoseidonTechnologies.caveworld.CaveWorld.start(CaveWorld.java:80) at com.P ...

How to monitor and respond to HTML modifications in a child component from a parent component in Angular framework

In the setup I have, there is a main component known as @Component({ selector: 'parent-comp' template: '<child-comp [inputData]="responseData"></child-comp> }) export class ChildComponent { public responseData: any; ...

iOS users may find that when a web page loads, it is often already scrolled halfway down

Encountering a problem with a long-scroll website that I'm currently developing. Whenever I access the page on my iPhone, the initial scroll position is consistently halfway down or near the bottom of the page. I've attempted to troubleshoot by d ...

"Encountering issue with jQuery $.ajax DELETE not triggering then() function

I have implemented some code within a Chrome extension that effectively utilizes the then() method from the xhr response when using $.ajax. if (request && request.action === "updateTask") { $.ajax({ type: "PUT", url: config.upda ...

Adjusting Navigation bar size according to the Media Screens/Device Width

Greetings! I am curious to know if it is feasible for my navigation bar to adjust its size according to different screen sizes. For instance, I would like the nav bar to be visible at a specific height on desktops and appear smaller at a different height o ...

Surprising quirks found in Material UI popover functionality

I am facing an issue with popovers on my webpage, where each line in a table has a popover. While all of them work correctly under the condition of opening by the item's id, the last item's popover briefly jumps to the top-right side of the scree ...

Utilizing Observable Data in Angular 4 TypeScript Components

Looking to extract and assign a JSON value obtained from an API into a variable. Here is an example: TS this.graphicService.getDatas().subscribe(datas => { this.datas = datas; console.log(datas); }); test = this.datas[0].subdimensions[0].entr ...

How do I initiate a TypeScript Node server via the terminal?

I'm trying to start this Node app written in TypeScript, you can find the code here. Although I have TypeScript installed, I'm unsure how to begin running the Node server. Can anyone help me with this? ...

What is the highest number that can be generated by the mt_rand() function in a Windows environment?

For my PHP application, I need to assign each user a unique numerical code. I am currently using mt_rand(0,100000000) to generate these codes and want to ensure that millions of different numbers are generated for millions of users without any repeats bein ...

How to customize a dropdown menu with the size property?

Can anyone help me with styling a select box that uses the size attribute? Most tutorials only cover single-item select boxes. Has anyone dealt with styling select boxes with the size attribute before? Here's an example of what I'm trying to acc ...