Reputation: 89
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!
Upvotes: 3
Views: 4451
Reputation: 4100
The following function is performed only once after the checkout is updated thanks to the updated_checkout
event.
Therefore:
#billing_country
field is changedupdate_checkout
(not "updated") call is executed to update the cartupdated_checkout
event) the custom AJAX calls are made (only if the checkout_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.
Upvotes: 4