简体   繁体   中英

php/jQuery check if username exists

I have been trying to create a system that checks if the selected username is already being used or not. I have come up with the following code.

function checkUsername(username,func){ 
    $.post("functions/checkUsername.php",{'username': username},function(data){ 
        if(data!='1'){ popup_alert('The username you selected already exists.','Username Exists','Close'); return false; }
        else{ window[func](); }
    });
}

checkUsername.php returns a 0 if the username exists and 1 if it is available. I have run many tests on that. My issue is that for some reason it is running the if statement before data is set. I have inserted a alert(data) before the if statement and it pops up with a 1 after the popup_alert is created.

function checkUsername(username,callback){ 
    $.post("functions/checkUsername.php",{'username': username},function(data){ 
    callback && callback(data);      
    });
}

...

checkUsername(username,function(data) {
  if(data!='1'){ popup_alert('The username you selected already exists.','Username     Exists','Close'); return false; }
    else{ window[func](); }
});

or you can use $.ajax

function checkUsername(username,func){ 
      $.ajax({
        type: 'POST',
        async: false, 
        data: {'username': username},
        url: 'functions/checkUsername.php',
        success: function(data) {
          if(data!='1'){ popup_alert('The username you selected already exists.','Username  Exists','Close'); return false; }
        else{ window[func](); }
        },
        error: function() {
          alert('Connection error!');
        }
      });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM