6
votes

I'm creating a custom woocommerce integrated theme for wordpress.

I have a blob on the top that displays the total number of items in the cart, I want to update this blob using Jquery (w/o reloading the page) I was able to increase the number of items by getting the current number in the blob and increasing it by +1 for each click, the problem is the add to cart has an option to select the number of items you want to add to the cart. So if I select 3 items and click the button the blob only increases by one.

I can create a way to get the number of items being added from the front-end but I think it's unnecessary. I want to be able to get the total number from PHP sessions using jquery so that on every click of add item or remove item I'll get the current number dynamically from the server.

What I have done so far is to create a reloadCart.php file that echos the cart total, here's the code

<?php
require('../../../wp-blog-header.php');
global $woocommerce;
echo $woocommerce->cart->get_cart_contents_count();
?>

When I visit this page it echos the current item totals, but I cant get this data from jquery, it's been sometime since I last used AJAX also I have not worked on web projects for a very long time, but with what I remember, the AJAX call that I'm making is right.

I have tried using the get() and post() functions of jquery as well as the normal ajax() function, but nothing seems to work. Can someone please help?

$(".ajax_add_to_cart").click(function () {
   /*$("#bag-total").html(function () {
        var bagTotal = parseInt($(this).html());
        return ++bagTotal;
    });*/
    alert('clicked');
    $.get("<?php echo get_template_directory_uri(); ?>/reloadCart.php", function(data){
        alert("Data: " + data);
    });
}); 

The lines that are commented are the ones that I was using previously, to add the cart total by getting the current cart number from the front-end.

Any help would be appreciated. Thanks in advance!

3
I am a tiny bit unclear, are you attempting to grab this value from JQuery after it is gathered using PHP? echo $woocommerce->cart->get_cart_contents_count(); or is reloadCart.php supposed to provide you with the updated data you need? -The simple solution on the first block of code is to not echo the value directly, PHP alters the page as it is being loaded with dynamic data, in your first snippet you are essentially echoing a line of text; to grab that in JQuery you simply need to assign the text into a selectable <p class="gotYa"> tagViaTech
Are you sure that "<?php echo get_template_directory_uri(); ?>/reloadCart.php" is the correct path to your php file and that your php file isn't running into any errors? What is the current alert that you are getting?Nick Parsons
Pretty sure. Once the page is rendered when I visit reloadCart.php it prints out the current number of items in the cart.Rohit Nair

3 Answers

38
votes

You should not use any reload to update the cart content count… Instead you should use the dedicated woocommerce_add_to_cart_fragments action hook that is Ajax powered.

1) The HTML to be refreshed: So first in your theme's header.php file you should need to embed the cart count in a specific html tag with a defined unique ID (or a class), for example something like:

$items_count = WC()->cart->get_cart_contents_count(); 
?>
    <div id="mini-cart-count"><?php echo $items_count ? $items_count : '&nbsp;'; ?></div>
<?php

or:

$items_count = WC()->cart->get_cart_contents_count();

echo '<div id="mini-cart-count"><?php echo $items_count ? $items_count : '&nbsp;'; ?></div>';

2) The code:

add_filter( 'woocommerce_add_to_cart_fragments', 'wc_refresh_mini_cart_count');
function wc_refresh_mini_cart_count($fragments){
    ob_start();
    $items_count = WC()->cart->get_cart_contents_count();
    ?>
    <div id="mini-cart-count"><?php echo $items_count ? $items_count : '&nbsp;'; ?></div>
    <?php
        $fragments['#mini-cart-count'] = ob_get_clean();
    return $fragments;
}

if you use a class in your html Tag, you will replace ['#mini-cart-count'] by ['.mini-cart-count']. This hook is also used to refresh the mini-cart content.

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Since few years global $woocommerce; + $woocommerce->cart is outdated and replaced by WC()->cart to access WooCommerce cart object.


If you need jQuery to force refresh that count, you can try wc_fragment_refresh or wc_fragments_refreshed delegated events, like:

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

or:

$(document.body).trigger('wc_fragments_refreshed');
0
votes

I have not used woocommerce before but one pretty simple option when you say in your post:

When I visit this page it echos the current item totals, but I cant get this data from JQuery

...would be to use a user-sided JavaScript variable for the display, and then just call the PHP update methods for adding items to your cart using AJAX (which I do not show below because you have not provided that code).

<?php
    //hardcoded value for $woocommerce->cart->get_cart_contents_count()
    $woocommerce = 59;
?>
<button class="ajax_add_to_cart">Add to cart</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    //user sided variable for PHP value
    var total = parseInt($(".totalCost").text()); 
    $(".ajax_add_to_cart").click(function(){
        total++;                     //add to cart
        $(".totalCost").text(total); //update
    });
});
</script>

<p class="totalCost">
    <?php echo json_encode($woocommerce); ?>
</p>

You can copy and test this snippet on: http://phpfiddle.org/

Basically in the above code, I set the PHP value as a paragraph text on page load and then read that value into a JS variable to mess around with the data on the client side of the application and then I update the display text as needed.

0
votes

For anyone who wants the proper ajax implementation, here is the way to go.

in functions.php

add_action('wp_ajax_cart_count_retriever', 'cart_count_retriever');
add_action('wp_ajax_nopriv_cart_count_retriever', 'cart_count_retriever');
function cart_count_retriever() {
    global $wpdb;
    echo WC()->cart->get_cart_contents_count();
    wp_die();
}

in your script file (assuming you have enqued the script file and passed the ajax object into the script. you also need to put this block into a setInterval or in some other jquery action.

var data = {
  'action': 'cart_count_retriever'
};
jQuery.post(ajax_object.ajax_url, data, function(response) {
  alert('Got this from the server: ' + response);
});