John Davidson

javascript - Changing shipping fields values in WooCommerce doesn't work

0 comments
Message:


In my WooCommerce store I have an external API with the map for picking shipping address. After user choose place of delivery on the map, shipping address is send from client to server using AJAX.


Here's my Javascript functions invoked every time user change shipping address:


const changeShippingAddress = (address, postalCode, city) => {
wp.ajax.post( "change_shipping_address", {
address,
postalCode,
city
} )
.done(function(response) {
alert(response);
})
.fail(err => {
alert("fail");
alert(err);
});
}

And here's my PHP code in functions.php:


add_action( 'wp_ajax_nopriv_change_shipping_address', 'mytheme_change_shipping_address' );
add_action( 'wp_ajax_change_shipping_address', 'mytheme_change_shipping_address' );

function mytheme_change_shipping_address() {
WC()->customer->set_shipping_address($_POST['address']);
WC()->customer->set_shipping_postcode($_POST['postalCode']);
WC()->customer->set_shipping_city($_POST['city']);

wp_send_json_success('success');
}

Values are sending properly from client to server with AJAX (I can read them on server side and send them back to client with wp_send_json_success), but the problem is, shipping fields aren't updated (after sending form, error about empty shipping fields shows up). Why is that happened? Is something wrong with my set_shipping functions?



My Answer:
To change shipping fields values in WooCommerce using JavaScript, you can use the following code snippet:

javascript
// Change shipping fields values
jQuery(document).ready(function($) {
// Change shipping country
$('select#shipping_country').val('US').change();

// Change shipping state
$('select#shipping_state').val('CA').change();

// Change shipping postcode
$('input#shipping_postcode').val('12345').change();
});


In this code snippet, we are using jQuery to target the shipping country, state, and postcode fields in WooCommerce and change their values to 'US', 'CA', and '12345' respectively. You can modify the values as needed to suit your requirements.

Make sure to enqueue this JavaScript code in your theme's functions.php file or in a custom JavaScript file that is loaded on the checkout page. This will ensure that the shipping fields values are changed when the checkout page is loaded.

Rate this post

3 of 5 based on 5333 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us