Why is this function returning "undefined"?

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

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

This is an asynchronous call:

$.post("username_check.php", {....

So the return statements in the callback happen long after usernameValid returns (and since it didn’t return anything when it was run, it’s undefined).

Where you have return false; you should call another function, for example: userNameInvalidFunction(), and something else for true…or just continue submitting, etc.

The alternative is to make your AJAX call synchronous…but I strongly recommend against this, since it’ll completely lock up the user’s browser while it executes.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply