I need to wait for the checkout to be updated when the billing country is changed before I can run some AJAX calls on Woocommerce.
jQuery('select#billing_country').change(function(){ $( document.body ).on( 'updated_checkout', function( e, data ) { //AJAX calls here }); });
The problem is some of these calls then update the checkout as well and this results in an infinite loop. Is there a way to just wait for the checkout to be updated once (only the first time) every time the billing country is changed? So something like this:
jQuery('select#billing_country').change(function(){ $when.firsttime( 'updated_checkout', function( e, data ) { //AJAX calls here }); });
Thank you!
Answer
The following function is performed only once after the checkout is updated thanks to the updated_checkout
event.
Therefore:
- The
#billing_country
field is changed - The AJAX
update_checkout
(not “updated”) call is executed to update the cart - Once the checkout is updated (with the
updated_checkout
event) the custom AJAX calls are made (only if thecheckout_is_updated
variable is false).
The checkout_is_updated
variable is initialized to “false” each time the entire page is updated.
// executes one or more instructions only once after checkout has been updated jQuery( function($) { // set a control variable var checkout_is_updated = false; // if the "#billing_country" field changes, update the checkout $('form.checkout').on('change', '#billing_country', function(){ $(document.body).trigger('update_checkout'); // after the checkout has been updated $( document.body ).on( 'updated_checkout', function(){ // just once if ( checkout_is_updated == false ) { /* * AJAX calls here */ checkout_is_updated = true; } }); }); });
The code has been tested and works.