首页 > 解决方案 > Jquery/Javascript global variable not updated from within (nested) function

问题描述

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

标签: javascriptjquery

解决方案


推荐阅读