JayCustom
Well-Known Member
Hey Guys,
How can I call a sync function for ajax url GET, and wait for a result (rather than returning "undefined" or an unfilled PROMISE ?
I have tried so many things and I can't get this function to work properly.
Parent Function:
The line that calls this is the:
Which references this predefined block:
So I am trying to call this function "checkPhoneExists" which will do the following:
And the Ajax Function:
I have tried everything I can think of to STOP RETURNING and WAIT FOR A RESULT!
How can I call a sync function for ajax url GET, and wait for a result (rather than returning "undefined" or an unfilled PROMISE ?
I have tried so many things and I can't get this function to work properly.
Parent Function:
Code:
checkValidity: function(input) {
for ( var i = 0; i < this.validityChecks.length; i++ ) {
var isInvalid = this.validityChecks[i].isInvalid(input);
if (isInvalid) {
this.addInvalidity(this.validityChecks[i].invalidityMessage);
}
var requirementElement = this.validityChecks[i].element;
if (requirementElement) {
if (isInvalid) {
requirementElement.classList.add('invalid');
requirementElement.classList.remove('valid');
} else {
requirementElement.classList.remove('invalid');
requirementElement.classList.add('valid');
}
} // end if requirementElement
} // end for
}
The line that calls this is the:
Code:
this.validityChecks[i].isInvalid(input)
Which references this predefined block:
Code:
var phoneValidityChecks = [
{
isInvalid: function(input) {
const regex = RegExp(/\d{10}$/);
return !regex.test(input.value);
},
invalidityMessage: 'Please enter a valid phone number',
element: document.querySelector('label[for="register_phone"] .input-requirements li:nth-child(1)')
},
{
isInvalid: function(input) {
checkPhoneExists(input.value).then(json => {
if (!Array.isArray(json['data']) || json['data'].length === 0)
return true;
var exists = json['data'][0];
return exists;
});
},
invalidityMessage: 'Please enter a unique phone number',
element: document.querySelector('label[for="register_phone"] .input-requirements li:nth-child(2)')
}
];
So I am trying to call this function "checkPhoneExists" which will do the following:
Code:
async function checkPhoneExists(phone) {
$.when(checkPhoneNumberAjax(phone)).done(function(result){
return result;
});
}
And the Ajax Function:
Code:
async function checkPhoneNumberAjax(phone) {
var username = 'User';
var password = 'Pass';
var url = 'http://127.0.0.1/app/api/api.php';
var postData = {
"type" : 'GET',
"action" : 'phone_exists',
"phone" : phone,
};
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
data: postData,
contentType: 'application/json',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic "+btoa(username+':'+password));
},
success: function(resultData){
return resultData;
}
});
await new Promise(resolve => setTimeout(resolve, 3000));
return true;
}
I have tried everything I can think of to STOP RETURNING and WAIT FOR A RESULT!