1

The Problem:

I am trying to display a JavaScript alert when AJAX is called. But the alert only fires successfully when I refresh the page.

Here is the start of the function which triggers the javascript IF cart items > 2:

So if there are more than 2 items in the Woocommerce cart, run the Javascript alert...

add_action( 'wp_footer', 'trigger_popup' );
function trigger_popup() {

  global $woocommerce;
  $maximum_num_products = 2;
  $cart_num_products = WC()->cart->get_cart_contents_count();

        if( $cart_num_products > $maximum_num_products ) {

Then I am trying to display the javascript alert when ajax is called:

I researched Global Ajax Event Handlers and I think $.ajaxComplete is whats needed, but it doesn't trigger the javascript. I'm also trying to set the URL Ajax JS Handler in an attempt to trigger the alert...

    ?>
<script src="https://unpkg.com/sweetalert2@7.20.1/dist/sweetalert2.all.js"></script>
        <script type="text/javascript">

                //EXECUTE FOR AJAX?
                $( document ).ajaxComplete(function(){

                //URL NEEDED FOR AJAX TO WORK?
                  url: '/?wc-ajax=add_to_cart',

                    // ALERT CODE HERE
                  swal(
                    'You added all the items!',
                    'Proceed to checkout?',
                    'success')
                    //END OF ALERT CODE

        })(jQuery);
        </script>

<?php
  }
}       

As FYI, This is the working version of the Javascript triggers the alert ON PAGE REFRESH, but not for AJAX:

If there are more than 2 items in the cart, AND I refresh the page. This successfully triggers the javascript alert.

    ?>
<script src="https://unpkg.com/sweetalert2@7.20.1/dist/sweetalert2.all.js"></script>
        <script type="text/javascript">
                  swal(
                    'You added all the items!',
                    'Proceed to checkout?',
                    'success')
        </script>
<?php
  }
}

How can I get the Javascript alert to trigger on Ajax OR check if the IF conditions have been met, each time Ajax is called?

Thanks!

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Giuls
  • 570
  • 11
  • 33

2 Answers2

2

Try the following code where jQuery code will send an ajax request on "added_to_cart" delegated event. On that request php will get the cart item count and will return it to jQuery. If that count met some condition, it will display your sweet-alert message:

// Wordpress Ajax: Get different cart items count
add_action( 'wp_ajax_nopriv_checking_cart_items', 'checking_cart_items' );
add_action( 'wp_ajax_checking_cart_items', 'checking_cart_items' );
function checking_cart_items() {
    if( isset($_POST['added']) ){
        // For 2 different cart items
        echo json_encode( sizeof( WC()->cart->get_cart() ) );
    }
    die(); // To avoid server error 500
}

// The Jquery script
add_action( 'wp_footer', 'custom_popup_script' );
function custom_popup_script() {
    ?>
    <script src="https://unpkg.com/sweetalert2@8.8.1/dist/sweetalert2.all.min.js"></script>
    <script src="https://unpkg.com/promise-polyfill@8.1.0/dist/polyfill.min.js"></script>
    <script type="text/javascript">
    jQuery( function($){
        // The Ajax function
        $(document.body).on('added_to_cart', function() {
            console.log('event');
            $.ajax({
                type: 'POST',
                url: wc_add_to_cart_params.ajax_url,
                data: {
                    'action': 'checking_cart_items',
                    'added' : 'yes'
                },
                success: function (response) {
                    if( response >= 2 ){
                        swal(
                            'You added all the items!',
                            'Proceed to checkout?',
                            'success'
                        );
                    }
                }
            });
        });
    });
    </script>
    <?php
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

enter image description here

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • This worked perfectly! Thank you so much for helping out!! It is very much appreciated. – Giuls May 20 '18 at 15:28
  • @Giuls You are very welcome… it was not so complicated as [this other one](https://stackoverflow.com/questions/50102637/checkout-distance-calculation-using-google-map-api-in-woocommerce-3-3/50433903#50433903) – LoicTheAztec May 20 '18 at 15:40
  • The only thing is that the JS doesn't seem to trigger if multiple quantities of the same item is added to the cart. So it only counts 10xTshirts as 1xTshirt? – Giuls May 20 '18 at 15:41
  • 1
    @Giuls Change `sizeof( WC()->cart->get_cart() )` to `WC()->cart->get_cart_contents_count()` … and it will do the trick. – LoicTheAztec May 20 '18 at 16:13
  • Spot on. Thanks! – Giuls May 20 '18 at 17:30
0

I would like to add that there is currently a plug-in that provides a rest api for the cart.

https://wordpress.org/plugins/cart-rest-api-for-woocommerce/

with that plugin you can listen for item added event and get the item count

(function($) {
  $(document.body).on("added_to_cart", function() {
    $.get("/wp-json/wc/v2/cart/count-items", function(data) {
      console.log(data)
    });
  });
})(jQuery);
Brian Kimball
  • 372
  • 3
  • 7