Link to home
Create AccountLog in
PHP

PHP

--

Questions

--

Followers

Top Experts

Avatar of Robert Granlund
Robert Granlund🇺🇸

WooCommerce Update Checkout With Ajax
I have a woocommerce shopping cart.  I need to be able to update the checkout to reflect no shipping charge.  I found the following code that can update the cart via ajax and it works great, except that it deletes the tax.  I guess I need to pass the tax rate via the AJAX?  Right now it is set to update the :
billing_state: billingstate,
billing_country : billingcountry,

Does any expert know how I should update the Tax?  I think the script is over writing it but I'm not 100% sure and unfortunately there is not a url I can share

function custom_checkbox_checker () 
	{
		if ( is_checkout() ) 
		{
			wp_enqueue_script( 'jquery' ); ?>
			<script>
			jQuery(document).ready( function (e) 
			{
				var $ = jQuery;
				if ( typeof wc_checkout_params === 'undefined' )
				return false;

				var updateTimer,dirtyInput = false,xhr;

				function update_shipping(billingstate,billingcountry) 
				{

					if ( xhr ) xhr.abort();

					$( '#order_methods, #order_review' ).block({ message: null, overlayCSS: { background: '#fff url(' + wc_checkout_params.ajax_loader_url + ') no-repeat center', backgroundSize:'16px 16px', opacity: 0.6 } });

						var data = {

						action: 'woocommerce_update_order_review',

						security: wc_checkout_params.update_order_review_nonce,

						billing_state: billingstate,

						billing_country : billingcountry,

						post_data: $( 'form.checkout' ).serialize()

						};

						xhr = $.ajax({

						type: 'POST',

						url: wc_checkout_params.ajax_url,

						data: data,

						success: function( response ) {

						var order_output = $(response);

						$( '#order_review' ).html( response['fragments']['.woocommerce-checkout-review-order-table']+response['fragments']['.woocommerce-checkout-payment']);

						$('body').trigger('updated_checkout');

						},

						error: function(code){

						console.log('ERROR');

						}

						});

				}

			jQuery('.state_select').change(function(e, params){

			update_shipping(jQuery(this).val(),jQuery('#billing_country').val());

			});
		});
</script>
    
<?php }

    }

    add_action( 'wp_footer', 'custom_checkbox_checker', 50 );

Open in new window

Zero AI Policy

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Julian HansenJulian Hansen🇿🇦

No specific experience with this particular issue but prepared to talk you through it.
update_order_review() function definition can be found here http://woocommerce.wp-a2z.org/oik_api/wc_ajaxupdate_order_review/
Does not appear to explicitly do anything with Tax but it does call calculate_totals() which might affect the result.

Where is tax currently being set?

Avatar of Robert GranlundRobert Granlund🇺🇸

ASKER

Is line 48 above over writing the current content of #order_review?  It is in that div ID where the tax is also previously written, then on change it disappears.

Avatar of Robert GranlundRobert Granlund🇺🇸

ASKER

@julian;

I think I know what I need to do to fix my issue but here is my problem, just taken a little father.  I need this jquery change function to initiate the following php function and I am not sure how to accomplish this.

The jQuery:
<script>

jQuery(function($) {
    var order_type = {
    	$checkout_form: $( 'form.checkout' ),
        init: function() {
            this.$checkout_form.on( 'change', 'select.order_type', this.check_for_in_store );
        },
        check_for_in_store: function(){
        	if(jQuery('select.order_type').val() == 'in_store'){
        		$( 'input[name^="shipping_method"][type="radio"]' ).each( function() {
        			
        			if($(this).val().indexOf('free_shipping') >= 0){
        				$(this).trigger('click');   
        			}
        		})
        	}
            //  THIS DOES NOT WORK   jQuery(document.body).trigger("update_checkout");
//  THIS IS WHERE I THINK I NEED TO CALL MY PHP FUNCTION

        }
    }

    order_type.init();
})

Open in new window


Here is the PHP Function:
<?php
function custom_checkbox_checker () 
	{
		if ( is_checkout() ) 
		{
			wp_enqueue_script( 'jquery' ); ?>
			<script>
			jQuery(document).ready( function (e) 
			{
				var $ = jQuery;
				if ( typeof wc_checkout_params === 'undefined' )
				return false;

				var updateTimer,dirtyInput = false,xhr;

				function update_shipping(billingstate,billingcountry) 
				{

					if ( xhr ) xhr.abort();

					$( '#order_methods, #order_review' ).block({ message: null, overlayCSS: { background: '#fff url(' + wc_checkout_params.ajax_loader_url + ') no-repeat center', backgroundSize:'16px 16px', opacity: 0.6 } });

						var data = {

						action: 'woocommerce_update_order_review',

						security: wc_checkout_params.update_order_review_nonce,

						billing_state: billingstate,

						billing_country : billingcountry,

						post_data: $( 'form.checkout' ).serialize()

						};

						xhr = $.ajax({

						type: 'POST',

						url: wc_checkout_params.ajax_url,

						data: data,

						success: function( response ) {
console.log('success today');
						var order_output = $(response);

						$( '#order_review' ).html( response['fragments']['.woocommerce-checkout-review-order-table']+response['fragments']['.woocommerce-checkout-payment']);

						$('body').trigger('updated_checkout');

						},

						error: function(code){

						console.log('ERROR');

						}

						});

				}

			jQuery('.state_select').change(function(e, params){

			update_shipping(jQuery(this).val(),jQuery('#billing_country').val());

			});
		});
</script>
    
<?php }

    }

    add_action( 'wp_footer', 'custom_checkbox_checker', 50 );
	

Open in new window


I do not understand line 14 of the jQuery
I also don't understand line 65 and 67 of the PHP

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Julian HansenJulian Hansen🇿🇦

In the first listing
$(this).trigger('click');

Open in new window

The code is checking the radio button - you could achieve this with the following code as well
$(this).prop({checked: true});

Open in new window

65-67 Is saying that when the <select> (with class .state-select - I am assuming the State dropdown) changes then call the update_shipping() (javascript) function which is defined earlier in the PHP and basically does an AJAX call back to the server to update the shipping.

As to your question in your earlier post line 48 - what appears to be happening is you are calling back to the server - it is sending back a rendered fragment which you are replacing into an element on the page. If that element contains the tax then the returned fragment would have to include the tax as well - otherwise it will get wiped.

Avatar of Robert GranlundRobert Granlund🇺🇸

ASKER

OK.  I just need to figure out how to include the tax!  The tough part is that there is almost Zero documentation and Woo won't support custom coding.  I will keep searching.  Thanks.

Avatar of Julian HansenJulian Hansen🇿🇦

Feel free to bounce ideas here - Woo programming is not easy as you say docs and examples are not readily available especially when you want to go outside the box - happy to help as a sounding board.

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Robert GranlundRobert Granlund🇺🇸

ASKER

What are your thoughts on the following:
When I change the order type from Phone to In-Store, it wipes the taxes.  This, I believe, comes from line 49 above:
 $( '#order_review' ).html( response['fragments']['.woocommerce-checkout-review-order-table']+response['fragments']['.woocommerce-checkout-payment']);

Taxes are in the .woocommerce-checkout-review-order-table
You can see in the two screenshots I have included.
Do you think that I need to pass the taxes in the AJAX as part of the update?  The code that I have found above is to update the checkout and price on state-change.  It will update the price when I change the shipping.
The two screen shots are from two different tests but show exactly how the taxes are there and then gone.
Before_Change.PNG
After_Change.PNG

ASKER CERTIFIED SOLUTION
Avatar of Julian HansenJulian Hansen🇿🇦

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.
Create Account
PHP

PHP

--

Questions

--

Followers

Top Experts

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.