WordPress Development Asked by Brian Bruman on October 30, 2021
What is the deal here?
JS FUNCTION ‘custom.js’
function validate() {
var email = jQuery("#billingemail").val();
if (isValidEmailAddress(email)) {
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {"action": "custome_ajax_email_check", "guestemail": email },
success: function(data){
data = jQuery.parseJSON(data);
if(data.result) {
alert('Email Exists');
return false;
} else {
alert('Email Does Exists');
return true;
}
}
});
} else {
return false;
}
}
JS ON CLICK ‘custom.js’
$('#mwb_logincoupon').on('click', '#validateguestemail', function (e) {
e.preventDefault();
validateemail = validate();
PHP AJAX
add_action( 'wp_ajax_custome_ajax_email_check', 'custome_ajax_email_check' );
add_action('wp_ajax_nopriv_custome_ajax_email_check', 'custome_ajax_email_check');
function custome_ajax_email_check(){
$email = $_POST['guestemail'];
// do check
if ( email_exists($email) ) {
$response->result = true;
}
else {
$response->result = false;
}
echo( json_encode( $response));
wp_die();
}
debugging the script the JS code goes into the success
function, so far as even triggering off the alert('Email Exists')
.. but the return
statement in the functon is never retrieved thus making validateemail
always return undefined
. Why?
Per @SallyCJ suggestion to use await
I construed this new function
async function doAjax(email) {
let result;
try {
result = await jQuery.ajax({
url: ajaxurl,
type: 'POST',
data: {"action": "custome_ajax_email_check", "guestemail": email }
});
return result;
} catch (error) {
console.error(error);
}
}
Then my validate()
function now just is simply
function validate() {
var email = jQuery("#billingemail").val();
if (isValidEmailAddress(email)) {
doAjax(email).then( (data) => ajaxCallResult(data) )
}
. . . . .
Then lastly
function ajaxCallResult(data){
data = jQuery.parseJSON(data);
. . . . . .
It is working.. very interesting, learning about await
then
, asynchronous
and synchronous
calls, etc
Answered by Brian Bruman on October 30, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP