The WooCommerce mini cart fails to refresh after items are added using AJAX

I have successfully implemented adding multiple items with quantities to the cart using AJAX. However, after adding a product, the mini cart is not updating as expected. I am calling WC_AJAX::get_refreshed_fragments() in my function.php and have a hook set up to update the cart (woocommerce_add_to_cart_fragments). What can be done to force the mini cart to update properly or what may need fixing in the code?

JS

// Array with products to add along with their quantities
productsToAdd 

$(document).on('click', '.buy-tovar', function (e) {
    e.preventDefault();         
    productsToAdd.forEach(function(item){
        var data = {
            action: 'woocommerce_ajax_add_to_cart',
            product_id: item['id'],
            quantity:  item['quantity']
        };
        $.ajax({
            type: 'post',
            url: wc_add_to_cart_params.ajax_url,
            data: data,
            async: false,
            success: function (response) {
                $('.buy-tovar').addClass("added");                      
            },
        });

    }); 
});

PHP

add_filter( 'woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment' );
function woocommerce_header_add_to_cart_fragment( $fragments ) {
    ob_start(); 
    ?>
    <a href="<?php echo wc_get_cart_url(); ?>" class="cart">
        <div class="img-block">
            <img src="<?php echo get_template_directory_uri();?>/image/cart.png" alt="">
            <span><?php echo count( WC()->cart->get_cart()); ?></span>
        </div>
    </a>
    <?php   
    $fragments['a.cart'] = ob_get_clean(); 
    
    return $fragments;
}

//AJAX 
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');

function woocommerce_ajax_add_to_cart() {
    
    $product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
    $quantity = absint($_POST['quantity']);
    $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
    $product_status = get_post_status($product_id);
    
    

    if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity) && 'publish' === $product_status) {

        do_action('woocommerce_ajax_added_to_cart', $product_id);

        if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
            wc_add_to_cart_message(array($product_id => $quantity), true);
        }
        
         WC_AJAX::get_refreshed_fragments();
    } else {

        $data = array(
            'error' => true,
            'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));

        echo wp_send_json($data);
    }

    wp_die();
} 

Answer №1

After encountering a problem, I was able to find a solution by including the following line in my JS:

$(document.body).trigger('wc_fragment_refresh');

This is the complete JS code snippet that helped resolve the issue:

document).on('click', '.buy-tovar', function (e) {
    e.preventDefault();         
    productsToAdd.forEach(function(item){
        var data = {
            action: 'woocommerce_ajax_add_to_cart',
            product_id: item['id'],
            quantity:  item['quantity']
        };
        $.ajax({
            type: 'post',
            url: wc_add_to_cart_params.ajax_url,
            data: data,
            async: false,
            success: function (response) {
                $('.buy-tovar').addClass("added");
                $(document.body).trigger('wc_fragment_refresh');
            },
        });

    }); 
});

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

.NET MVC - Preventing Ajax.BeginForm from being compromised

I am facing security issues with an Ajax-based form in my .Net MVC Web Application. Despite implementing Google reCaptcha, the form is still vulnerable to hacks and spam messages. @using (Ajax.BeginForm("ContactSend", "Home", null, new ...

Preparing data before using Kendo UI upload function is essential

I need to pass a data (specifically a GUID) to the upload method of the kendoUpload, so that a particular MVC Controller action method can receive this data each time the upload occurs. $("#propertyAttachmentUpload").kendoUpload({ async: { ...

Exploring the power of jQuery's Ajax feature combined with the POST method

I'm facing an issue with two files named basic.php and pptimeline.php. The objective is to choose a value from a combobox in basic.php, process it in pptimeline.php, and then display the result back in basic.php. However, I haven't been able to a ...

How to Show PHP Errors using Serverpilot

I am in the process of updating my website from php5.6/mysql to php7.0/mysqli. Currently, I am using digitalocean with serverpilot.io as my hosting provider. However, I am facing an issue where I am unable to display PHP errors; instead, it just shows a wh ...

Encountering a problem with AJAX displaying error code 80020101 while attempting to retrieve a string from a

I encountered an error while running my code: Microsoft JScript runtime error: Could not complete the operation due to error 80020101. I came across this thread on Stackoverflow that talks about a similar issue: Ajax request problem: error 80020101 var d ...

Laravel request pre-loading system

My Laravel application has a search function on the homepage (home.blade.php) that queries the database and displays results on the results page (results.blade.php). Despite using Elastic search to optimize speed, the search still takes around 10 seconds d ...

re-establishing multiple selections in a dropdown menu in PHP/HTML

Hey, I've got this multi-select listbox... <select id="extfeat" name="extfeat[]" size="6" multiple=""> <option value="Wheel_Chair Accessible">Wheel Chair Accessible</option> <option value="Fruit_Trees">Fruit Trees& ...

I encountered a frustrating problem while trying to generate a direct URL from YouTube using PHP

After conducting research on how to obtain direct URLs from YouTube videos, similar to the one posed in this query: How to get a direct URL of video from YouTube URL? [closed] I have successfully created a basic script using PHP to generate a direct URL f ...

Error message: The Liferay JavaScript Function has not been defined

I am a newcomer to Liferay and have been attempting to utilize Ajax within my scripts, but unfortunately, the code does not seem to load correctly in the browser. I even tried testing it by simply adding an alert. Every time I try, I encounter the "functi ...

Validating PUT/PATCH requests in Laravel 5.2's REST controller

I'm encountering an issue with Laravel that is resulting in a 405 MethodNotAllowedHttpException error. I've been attempting to implement validation for update requests in my resource PointController, but it seems that the validation rules defined ...

The save button is not functioning properly

Currently, I am in the process of creating an order form. One of the key functionalities I have been working on is the "save changes function". This feature allows users to make changes to the table and then update the database by clicking a specific butto ...

Sending emails with SMTP in JavaScript using the mailto form

I'm facing a challenge with my form. I am looking for a way to have the Send-email button trigger mailto without opening an email client, instead automatically sending via JavaScript (smtp). I'm not sure if this is achievable or if I'm askin ...

Is there a way to insert and store a personalized field in the WordPress Gutenberg (block editor) dashboard?

https://i.stack.imgur.com/FZvts.png I'm currently working on my portfolio and am looking to include a gallery field. I couldn't figure out how to add a custom field in the screenshot provided. Does anyone have any insights on how this can be ach ...

Live search with AJAX, navigate to a different page, and showcase the findings

I currently have multiple web pages that all feature the same search form. What I want to achieve is for the results page to load dynamically as the user starts typing, replacing the current page and displaying all relevant items found. How can I implement ...

Error message "Authorization issue occurred while trying to call a function in the PHP webservice."

I am facing an issue with calling a web service. It successfully connects and returns its methods, however, when I call one of the functions, it throws an unauthorized error. Here is my code try { $service = new SoapClient("http://www.go-to-orbit.com/oo ...

The information from the ajax code is not appearing on the screen as expected

I am currently working on a project where I have li tags containing links to various pages. My goal is to create a search feature that will be triggered by clicking on a specific li tag. In this case, when the user clicks on the li tag labeled 'Field ...

When using node.js and prototype, the responseText function will concatenate the current response text with the

Here is a node.js function I wrote that utilizes res.write: function ping(){ res.write(JSON.stringify({"datatype":"ping"})); setTimeout(ping, 30000); } Below is the client request written in prototype: this.pushconnection = new Ajax.Request( ...

Adding associations with models in Laravel post-updateAfter updating Laravel, you can

I am using a role package that stores relational data in my database, specifically with a users table and a user_roles table containing foreign keys. When updating the model, I utilize the following code: $user = User::findOrFail($id); $user-> ...

Unveiling the Art of JSON Parsing and Effectively Accessing

I am currently using CURL for sending a request and the response received is in JSON format. I need help with parsing this data and inserting it into my database. <?php $url = 'http://example.com/api/endpoint'; $phoneNumber = '123456789 ...

The ajax success() function is failing to function properly when attempting to make a call

The button's onClick() event is not navigating anywhere. There seems to be an issue with the success() function of the ajax call. Unfortunately, I am new to this and unable to pinpoint the problem. var currentAuthor=""; var currentQuote=""; $(documen ...