I have a function to validate an email address that checks for errors and then increases the variable "errorCount" by 1 if an error has occured. I have hooked up the email validation to an ajax call that returns whether or not an inputted email is already in my database however I cannot get the variable errorCount to increment outside of the ajax function. How can I accomplish this? I have tried declaring the variable "errorCount" as a global variable with no luck.
All outside code works so that the ajax function is successful and my email address errors all show when they are fired. The only thing I'm missing is returning the incremented variable outside the ajax function so the errorCount increases.
Thanks
Code:
var validateEmailAddress = function () {
var errorCount = 0;
var emailAddress = $('#email-address');
var emailAddressConfirm = $('#email-address-confirm');
if (!isValidEmailAddress(emailAddress.val())) {
$('#email-address-format-error').show();
errorCount++;
}
if (!isValidEmailAddress(emailAddressConfirm.val())) {
$('#email-address-confirm-format-error').show();
errorCount++;
}
if (emailAddress.val() != emailAddressConfirm.val()) {
$('#email-address-match-error').show();
errorCount++;
}
var vars = { email: $('#email-address').val() }
console.log(vars);
$.ajax({
url: "http://localhost:8888/check_email.php",
data: vars,
type: "POST",
dataType: "json",
success: function (data) {
console.log(data);
if (data.emailConfirm === 'true') {
$('#email-address-match').show();
errorCount++;
}
}
})
return errorCount;
}