0

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.

2
  • How did you find out that it runs before the data is set ? Did you try looking over with FireBug or something like it ? Commented Mar 12, 2013 at 18:59
  • It won't run before. That is the success callback. So that is a very wrong assumption Commented Mar 12, 2013 at 19:00

1 Answer 1

1
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!');
        }
      });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.