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!
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
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:
Code goes in function.php file of your active child theme (or active theme). Tested and works.