In my online store, there are two standard shipping methods - Flat Rate and Free Delivery. I added a plugin for distance delivery.
Thus, when a customer fills in the City and Address fields when placing an order, new shipping methods must be added. But new deliveries are not visible until I select Flat Rate or Free Delivery.
As I understand it, I do not have automatic updating of shipping methods depending on the filling of the fields.
I found and edited this code:
add_action('wp_footer', 'woocommerce_custom_update_checkout', 50);
function woocommerce_custom_update_checkout() {
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery( document ).ready(function( $ ) {
$('#billing_address_1').click(function(){
jQuery('body').trigger('update_checkout', { update_shipping_method: true });
});
});
</script>
<?php
}
}
But until I click on the filled field a second time, the delivery method is not updated.
I want to connect with AJAX. How can I edit the code so that the result of using AJAX is visible immediately without clicking on the filled field again?
Currently you have to click on the billing_address_1 field in order to trigger the event listener and update your fields, because your code says so!
There are multiple ways to solve the issue. For example, instead of listening for a click event, you could add a different event listener.
To start off, you could listen for an on change event. This will happen when the value of the address field has been changed and the user clicked/tabbed out of the billing_address_1 field:
add_action('wp_footer', 'woocommerce_custom_update_checkout', 50);
function woocommerce_custom_update_checkout()
{
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery(document).ready($ => {
$('#billing_address_1').on('change', () => {
$('body').trigger('update_checkout', {
update_shipping_method: true
});
});
});
</script>
<?php
}
}
Another event listener you could use here is input event listener. This will happen every time the value of billing_address_1 field is being changed. This will fire off even with a press of the space key, backspace key etc.
add_action('wp_footer', 'woocommerce_custom_update_checkout', 50);
function woocommerce_custom_update_checkout()
{
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery(document).ready($ => {
$('#billing_address_1').on('input', () => {
$('body').trigger('update_checkout', {
update_shipping_method: true
});
});
});
</script>
<?php
}
}
Another event that could be helpful here is on blur event. This event will fire off when the user clicks/tabs out of the billing_address_1 field. The difference between this event and on change event is that when you listen for this event, update will happen even when the value of the billing_address_1 field has not been changed.
add_action('wp_footer', 'woocommerce_custom_update_checkout', 50);
function woocommerce_custom_update_checkout()
{
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery(document).ready($ => {
$('#billing_address_1').on('blur', () => {
$('body').trigger('update_checkout', {
update_shipping_method: true
});
});
});
</script>
<?php
}
}
Now depending on how you'd like to structure your code and the logic behind it, you could use these events at the same time:
add_action('wp_footer', 'woocommerce_custom_update_checkout', 50);
function woocommerce_custom_update_checkout()
{
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery(document).ready($ => {
$('#billing_address_1').on('change input blur', () => {
$('body').trigger('update_checkout', {
update_shipping_method: true
});
});
});
</script>
<?php
}
}
How can I edit the code so that the result of using AJAX is visible immediately without clicking on the filled field again?
I think the last solution is what you're looking for! Using all of those event listeners together will make sure that your shipping method is getting updated constantly.
Related
Hi,
i have a site that displays various projects as posts, each project has its own pdf file, uploaded via a file custom field for that post.
For the moment there's just a dynamic button as you can see in this example:
https://www.stefanomengoli.it/sm21/progetti/vivere-nelle-nuvole-progetto-di-bioarchitettura-per-un-loft-casa-sullalbero/
What i need is the user to be able to download or be redirected to the correct file after CF7 submission based on the project he/she is on.
I tried this code and it works with a specific url, but what i need is to put an acf url that dynamically shows the correct file as I said based on the project the visitor is on.
add_action( 'wp_footer', 'example_download' );
function example_download() {
?>
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
if ( '946' == event.detail.contactFormId ) {
window.open('https://www.example.com/wp-content/uploads/2021/05/my-document.php',
'_self');
}
}, false );
</script>
<?php
}
You just need to echo the custom field in the window.open
This should work. Just replace your_field with your ACF field name
add_action( 'wp_footer', 'example_download' );
function example_download() {
global $post;
?>
<script type="text/javascript">
document.addEventListener('wpcf7mailsent', function (event) {
if ('946' == event.detail.contactFormId) {
window.open('<?php the_field('your_field', $post->ID);?>',
'_self');
}
}, false);
</script>
<?php
}
I am trying to create a step in checkout to confirm your order. I'm thinking when the place order button is clicked AND the checkout fields are valid I could run some JS to show a modal or whatever.
Is there a JS trigger/event similar to checkout_place_order that runs after validation? For example, I can use the following but it happens before validation. Maybe there is a way to trigger validation from inside there and display my modal based off that?
var checkout_form = $('form.checkout');
checkout_form.on('checkout_place_order', function () {
// do your custom stuff
return true; // continue to validation and place order
return false; // doesn't validate or place order
});
There is also the woocommerce_after_checkout_validation hook but I am not sure how to utilize it to achieve what I'm after.
I am open to ideas...
I was able to figure this out finally, Its more of a workaround since I don't think there is a clear way to do this.
As soon as the "Place Order" button is clicked, we use the checkout_place_order event to place a hidden field with a value set to 1.
var checkout_form = $('form.checkout');
checkout_form.on('checkout_place_order', function () {
if ($('#confirm-order-flag').length == 0) {
checkout_form.append('<input type="hidden" id="confirm-order-flag" name="confirm-order-flag" value="1">');
}
return true;
});
Next, we use the hook woocommerce_after_checkout_validation to check our hidden input and if the value is 1 add in error (This stops the order from going through).
function add_fake_error($posted) {
if ($_POST['confirm-order-flag'] == "1") {
wc_add_notice( __( "custom_notice", 'fake_error' ), 'error');
}
}
add_action('woocommerce_after_checkout_validation', 'add_fake_error');
Last, we use the checkout_error event to determine if there was a real validation or if if there is only 1 error, the error we added. If there is only 1 error it means validation passed so we can show our modal (or whatever you need to do).
$(document.body).on('checkout_error', function () {
var error_count = $('.woocommerce-error li').length;
if (error_count == 1) { // Validation Passed (Just the Fake Error I Created Exists)
// Show Confirmation Modal or Whatever
}else{ // Validation Failed (Real Errors Exists, Remove the Fake One)
$('.woocommerce-error li').each(function(){
var error_text = $(this).text();
if (error_text == 'custom_notice'){
$(this).css('display', 'none');
}
});
}
});
Inside my modal I have a confirm button that sets our hidden field value to nothing and clicks the place order button again. This time the order will go through because we are checking for the hidden input value of 1.
$('#confirm-order-button').click(function () {
$('#confirm-order-flag').val('');
$('#place_order').trigger('click');
});
As far as I know, there is no hooks in between validation and order creation process, that will allow you to interact with customer, making some actions.
Using jQuery and Sweet Alert component (SWAL 2), here is an example of code that will disable the "Place Order" button displaying a Sweet Alert with confirmation buttons. It's not perfect, but it answers partially your question.
Once customer will confirm, the "Place Order" button will be enabled back and it will be triggered by the codeā¦ If the customer use the cancel button, Checkout review order will be refreshed (Ajax).
The code:
add_action( 'wp_footer', 'checkout_place_order_script' );
function checkout_place_order_script() {
// Only checkout page
if( is_checkout() && ! is_wc_endpoint_url() ):
// jQuery code start below
?>
<script src="https://unpkg.com/sweetalert2#8.8.1/dist/sweetalert2.all.min.js"></script>
<script src="https://unpkg.com/promise-polyfill#8.1.0/dist/polyfill.min.js"></script>
jQuery( function($){
var fc = 'form.checkout',
pl = 'button[type="submit"][name="woocommerce_checkout_place_order"]';
$(fc).on( 'click', pl, function(e){
e.preventDefault(); // Disable "Place Order" button
// Sweet alert 2
swal({
title: 'Are you sure?',
text: "You are about proceed the order",
type: 'success',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: "Yes let's go!"
}).then((result) => {
if (result.value) {
$(fc).off(); // Enable back "Place Order button
$(pl).trigger('click'); // Trigger submit
} else {
$('body').trigger('update_checkout'); // Refresh "Checkout review"
}
});
});
});
</script>
<?php
endif;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
I'm late to the party, but wanted to share a variation of the answers above
jQuery(document).ready(function($){
/* on submit */
$('form#FORMID').submit( function(e) {
/* stop submit */
e.preventDefault();
/* count validation errors */
var error_count = $('.woocommerce-error li').length;
/* see if terms and conditions are accepted */
var terms = $('input#terms').is(':checked');
/* if there are no validation errors and terms are accepted*/
if( error_count == 0 && terms ) {
/* trigger confirmation dialogue */
if( confirm('Are you sure?') ){
/* resume default submit */
$(this).unbind('submit').submit();
} else {
/* do nothing */
e.stopPropagation();
}
}
});
});
I got a fast and simple JS decision for myself in this case (there were woocommerce and stripe forms). That is based on preventing the checkout button from submit but still makes forms verifications.
// making the wrap click event on dinamic element
$('body').on('click', 'button#place_order_wrap', function(event) {
// main interval where all things will be
var validatoins = setInterval(function(){ happen
// checking for errors
if(no_errors==0){
// making the setTimeout() function with limited time like 200ms
// to limit checkout function for just make verification
setTimeout(function(){
// triggering original button
$('button#place_order').click();
// if there some errors, stop the interval, return false
if(($('element').find('ul.woocommerce_error').length!==0)||($('element').find('.woocommerce-invalid-required-field').length!==0)){
clearInterval(validatoins);
return false;
}else{
no_errors=1;
}
}, 200);
}
if(no_errors==1){
// same error checking
if($('#step5').find('ul.woocommerce_error').length!=0||($('#step5').find('.woocommerce-invalid-required-field').length!==0)){
// if there some errors, stop the interval, return false
clearInterval(validatoins);
return false;
}
setTimeout(function(){
// if no errors
if(($('#step5').find('ul.woocommerce_error').length==0)&&($('#step5').find('.woocommerce-invalid-required-field').length==0)){
// do something, mark that finished
return false;
}
}, 1000);
// if something finished
if() {
setTimeout(function(){
// trigger original checkout click
$('button#place_order').click();
clearInterval(validatoins);
}, 1000);
}
}
}, 1000);
}
I am wondering if someone can help me with the following code. I am trying to set some conditional html dependent on which payment method the user selects on checkout. On the payment method page I am using the following function to update the payment method information:
function cart_update_script() {
if (is_checkout()) :
?>
<script>
jQuery( function( $ ) {
// woocommerce_params is required to continue, ensure the object exists
if ( typeof woocommerce_params === 'undefined' ) {
return false;
}
$checkout_form = $( 'form.checkout' );
$checkout_form.on( 'change', 'input[name="payment_method"]', function() {
$checkout_form.trigger( 'update' );
});
});
</script>
<?php
endif;
}
add_action( 'wp_footer', 'cart_update_script', 999 );
On the final checkout page I am then getting that selected payment method with this bit of code:
<?php $chosen_gateway = WC()->session->chosen_payment_method; ?>
Then I am using conditional statements like the following:
<?php if ( $chosen_gateway == 'stripe' ) { ?>
//do this
<?php } ?>
My problem is that I am not getting dynamic information when the user changes payment method. Sometimes the code works but sometimes it still thinks a different payment method was selected. Any help would be great!
I am using woocommerce plugin and braintree extension of woocommerce for payment. I have enabled both card and paypal payment of woocommerce braintree to checkout. I am trying to figure out how to know which payment gateway the user selects before user actually checkouts and pays. Any hooks under woocommerce or braintree to find either credit card radio button or paypal payment radio button is checked for payment.
However i know we can detect the gateway used for the particular order after successful payment but i want the selected gateway information before payment completes within checkout page. Any Help?
You can detect chosen Payment Method with some basic JavaScript on checkout page and run your custom code with PHP by hooking into woocommerce_checkout_update_order_review action.
First,
you also should place JS code on checkout page, checkout template or in header/footer of your theme, so you can detect when the user has changed payment method option and run your own code after that.
JS code:
jQuery(document).ready( function() {
jQuery( "#payment_method_bacs" ).on( "click", function() {
jQuery( 'body' ).trigger( 'update_checkout' );
});
jQuery( "#payment_method_paypal" ).on( "click", function() {
jQuery(document.body).trigger("update_checkout");
});
jQuery( "#payment_method_stripe" ).on( "click", function() {
jQuery(document.body).trigger("update_checkout");
});
});
Notice that for each payment method you have active you should add 'Click' event. It gives you option to fine tune when your custom code is triggered.
To prevent click event to run ONLY ONCE you should add next block of JS code below first one.
jQuery( document ).ajaxStop(function() {
jQuery( "#payment_method_bacs" ).on( "click", function() {
jQuery(document.body).trigger("update_checkout");
});
jQuery( "#payment_method_paypal" ).on( "click", function() {
jQuery(document.body).trigger("update_checkout");
});
jQuery( "#payment_method_stripe" ).on( "click", function() {
jQuery(document.body).trigger("update_checkout");
});
});
It's the same code only that is triggered after ajax.
In both JS blocks of code add your payment options that you are actually use.
After that you put your custom PHP code that hooks into checkout like this:
if ( ! function_exists( 'name_of_your_function' ) ) :
function name_of_your_function( $posted_data) {
// Your code goes here
}
endif;
add_action('woocommerce_checkout_update_order_review', 'name_of_your_function');
This code can be placed in functions.php.
Here is complete PHP code that detects and run when specific payment option is chosen on checkout page:
function name_of_your_function( $posted_data) {
global $woocommerce;
// Parsing posted data on checkout
$post = array();
$vars = explode('&', $posted_data);
foreach ($vars as $k => $value){
$v = explode('=', urldecode($value));
$post[$v[0]] = $v[1];
}
// Here we collect payment method
$payment_method = $post['payment_method'];
// Run code custom code for each specific payment option selected
if ($payment_method == "paypal") {
// Your code goes here
}
elseif ($payment_method == "bacs") {
// Your code goes here
}
elseif ($payment_method == "stripe") {
// Your code goes here
}
}
add_action('woocommerce_checkout_update_order_review', 'name_of_your_function');
I hope this helps!
This is a very powerful option to run all your custom logic on the checkout page!
<script type="text/javascript">
<!--//
// on DOM ready
$(document).ready(function (){
$("#current_rev").html("v"+$.jnotify.version);
$("a.example").bind("click", function (e){
// prevent default behavior
e.preventDefault();
var $ex = $($(this).attr("href")), code = $.trim($ex.text());
// execute the sample code
$.globalEval(code);
});
// style switcher
$("button.css_switcher").click(function (){
switchCSS(this.title);
});
});
//-->
</script>
Instead of using click events like [Run] and [Run]
How can I call events if a condition is true or false?
<?php
if (true){
[Run]}else{
[Run]}
?>
You mean "trigger" events? Your question is a bit confusing.
You can just add $("#example-1").trigger("click") to the document.ready function.
So if a condition is true on the server side it will do something on the client side when the page gets sent to the user.
Make sure you attach the click event before you trigger it.
$(function () {
// all event binds and other code
<?php
if ( $trigger ) {
echo "$('#".$element_id."').trigger( 'click' )";
}
?>
}
Make $trigger a true false and give all your links ids and pass the id as $element_id