I am attempting to prevent WPForms from going to the next page until after my Ajax function has run. I am working on a multi-page form for a custom them and need to run a form validation to check if a user has already been created with that email. I could find no settings for this inside WPForms so began working on a custom Ajax function alongside a PHP function.
`jQuery(document).ready(function() { // Use event delegation to handle click on the "Next" button jQuery(document).on('click', '.wpforms-page-next', function(e) {
//pevent the default action of the button
e.preventDefault();
// Get the current page of the form
var currentPage = jQuery(this).data('page');
// Check if we are on the first page of the form
if (currentPage === 1) {
e.preventDefault();
// Get the email address from the form field
var email = jQuery('#wpforms-902-field_5').val();
console.log(email);
// Perform your AJAX request and response handling here
jQuery.ajax({
url: ajaxurl,
//choose the type of request
type: 'POST',
data: {
//run action launching the function
action: 'check_email_availability',
//pass the email address to the function
email_availability: email,
},
success: function(response) {
if (response === 'unavailable') {
console.log('unavailable')
// Show an error message for duplicate email
jQuery('#error-message').text('This email is already in use.');
} else {
console.log('available')
// If email is available, proceed to the next page
//jQuery( '.wpforms-page-next' ).click();
}
}
})
}
});
}); `
This is my ajax function, I have tested the function itself and it is working perfectly the only issue is that it runs after the WPForm has already gone from the first page to the second. I have successfully received both unavailable and available in the console.
Here is my php for reference.
add_action('wp_ajax_check_email_availability', 'check_email_availability'); add_action('wp_ajax_nopriv_check_email_availability', 'check_email_availability');
function check_email_availability() { global $wpdb;
if (isset($_POST['email_availability'])) {
$email = sanitize_email($_POST['email_availability']); // Corrected the key here
$user = $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM ilearn_students WHERE email = %s",
$email
)
);
$response = $user ? 'unavailable' : 'available'; // Reversed the response here
echo $response;
}
wp_die();
}
I have tried placing the e.preventDefault() in several different positions, I have tried removing the ajax and instead returning false, trying to break mine and the forms Ajax to no avail.
I have wrapped the Ajax inside a timeout function to try and ensure the ajax was read before the form moved to the next page, which also failed.
Any suggestions or advice would be greatly appreciated.