This question already has an answer here:
I have a form-validation function which validates and also checks to see if the username is taken or not (ajax).
This is how I call the code:
function validate(){
if(usernameValid()){
return true;
}
else {
return false;
}
}
I also alert the function in order to see what it returns:
alert(usernameValid());
The problem is that the alertbox alerts "Undefined" in some cases, so my validation wont jump to the next field, it hangs. To be more specific, it alerts "Undefined" in all cases except when the "length===0", then it alerts false which is correct.
Here is the usernameValid function:
function usernameValid(fld) {
if( $('#username').val().length !== 0 ) {
$.post("username_check.php", {
username: $('#username').val()
}, function(response){
response = escape(response);
if(response==1){
$('#username_error_invalid').show();
$('#username_error_empty').hide();
$('#username_error_taken').hide();
return false;
}
else if(response==2){
$('#username_error_taken').show();
$('#username_error_invalid').hide();
$('#username_error_empty').hide();
return false;
}
else {
$('#username_error_taken').hide();
$('#username_error_invalid').hide();
$('#username_error_empty').hide();
return true;
}
});
}
else{
$('#username_error_empty').show();
$('#username_error_invalid').hide();
$('#username_error_taken').hide();
return false;
}
}
Anybody know what is wrong, ie why the code returns undefined in the cases where I test the "response" variable?
BTW: The validation itself for the username works (error is displayed when it should etc), but it returns undefined...
Thanks
</div>