Reputation: 281
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.
Upvotes: 0
Views: 669
Reputation: 26
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!');
}
});
}
Upvotes: 1