I'm lost and not exactly sure what to look up when it comes to this. I know it might have something to do with jQuery promises. So, quick to the point, i'm trying to return a "pass" variable as boolean to check whether a email is valid or not. Instead of passing false with a value = "asdf", it's still passing true. I know it's because of the asynchronous request, I'm just not exactly sure how to defer that variable. Code is below:
console.log( this.newValidate($('#forgottenPwdForm'))); // Returns true
newValidate: function(form){
var $form = form,
errmsg = function(msg){
return '<span class="error" style="text-align:right; margin: 2px 15px; color:red;">' + msg + '</span><br/>';
};
// Check email / username
// Needs to run 2 validations. Is the email valid? And is it duplicate if valid
if($form.find('.email').length)
$form.find('.email').each(function(){
var email = escape($(this).val().trim()),
valid = true,
duplicate = false,
pass = true;
// Check if email is valid
$.when(
$.get('/service/account/ajaxdata?method=validemail&emailaddr='+email, function(res){
console.log(res);
valid = res;
}),
$.get('/subscribe/check_email?email=' + email, function(data) {
if(data){
duplicate = false; }
})
).then(function(){
if(valid == 0){
var error = errmsg("Email is not valid.");
pass = false;
console.log(pass);
}
else {
// Now that the email is valid, we need to check if it's duplicate
if(duplicate == false) {
$('.email').addClass('emailError');
pass = false;
}
else {
if($('.email').hasClass('emailError')) {
$('.email').removeClass('emailError');
$('.email').removeClass('error');
}
pass = true;
}
}
});
if(pass == false) return pass;
});
Code returns true when it should be returning false. Again, I know it's something to do with the $.get request and the variable being out of scope, I'm just not sure how to defer it.