Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript execute function on Woocommerce checkout event

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!

like image 572
Eliott Avatar asked Jun 13 '26 03:06

Eliott


1 Answers

The following function is performed only once after the checkout is updated thanks to the updated_checkout event.

Therefore:

  1. The #billing_country field is changed
  2. The AJAX update_checkout (not "updated") call is executed to update the cart
  3. Once the checkout is updated (with the updated_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.

like image 64
Vincenzo Di Gaetano Avatar answered Jun 18 '26 00:06

Vincenzo Di Gaetano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!