0

I am trying to get a global variable updated from within a (nested) function to validate if an email address exists in the database or not. But for some reason it does not work and the variable is not updated. Does anyone has an idea what I am doing wrong?

var validate = true;

/* More stuff that works fine */

element.find("input[type=email][data-checkexist='true']").each(function() {
    var email_to_check = $(this).val();
    var self = $(this);
    $.get('./inc/register_functions.php?checkemail=' + email_to_check, function(data) {
        if(data === 'emailexist'){
            self.after('<div class="alert alert-danger validate-alert">' + messages.emailexist + '</div>');
            validate = false;
            alert(validate); /* Returns false. Correct */
        }
    });
});
alert(validate); /* Returns true which is wrong */

The second alert does not return the updated value of validate. The PHP script returns the correct "emailexist" value

JoshBali
  • 3
  • 3
  • Check response or check `if` condition! – Vinay Kaklotar Jan 24 '20 at 04:34
  • [var](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) has pretty weird scoping. Consider using [let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) for stuff you need to overwrite and [const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) for things that don't need to be overridden. – volt Jan 24 '20 at 04:36
  • Response from PHP (emailexist) is correct. First alert returns false as expected but second returns true. – JoshBali Jan 24 '20 at 04:36

0 Answers0