0

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;

}
John M
  • 1
  • 1
  • You **cannot** `return` a value from asynchronous handler but you **can** use the `errorCount` value inside `success` function (for example `alert(errorCount);`. – Alex Kudryashev Aug 27 '17 at 18:14

1 Answers1

-1

Move you errorCount variable outside of your function validateEmailAddress, because every time you call your function this variable will be initialized to 0, and we cannot return variables from asynchronous calls to functions.

pOoOf
  • 119
  • 8
  • Moving the variable outside of the function would significantly change the behavior of the code. And would not correct the problem of trying to return a value from an asynchronous function. – David Aug 27 '17 at 18:19
  • "The ajax function" more likely refers to the actual function called `$.ajax()`, outside of which the variable is clearly not being incremented specifically for the reasons outlined in the linked duplicate. – David Aug 27 '17 at 18:28