Validate.Custom return false and return true using livevalidation

572 Views Asked by At

I am using LiveValidation to validate my forms, I am trying to validate a username with ajax call using livevalidation. I am having trouble on getting the return value if the return is either true of false so that I can display if username is available or not, But in this case it always return username is not available.

HTML:

   <input type="text" id="username" name="username" />

JS:

   var username = new LiveValidation('username');
   username.add( Validate.Presence );
   username.add( Validate.Length, { minimum: 4, maximum: 10 } );
   username.add( Validate.Custom, { against: function() { return    check_username_availability() }, args:'Username Available' , failureMessage: 'Username is    Not Available' } ); 

  $.post(base_url+'cms-profile/profile_ajax/valid_username/',{username : $("#username").val()},function(data){

    if( data.success == 'no' )
     {
       return false;
     }

     if( data.success == 'yes' )
     {
        return true;
     }
    });

PHP:

   $check_username = 'some query here';

   if($check_username == true){
        $output = '{ "success": "no" }';
   }else{
       $output = '{ "success": "yes" }';
   }

   $output = str_replace("\r", "", $output);
   $output = str_replace("\n", "", $output);

   echo $output;
1

There are 1 best solutions below

0
On

I don't get why you're complicating things like that. I would use JSON, that's what it is for:

PHP:

echo json_encode( $check_username ); 
// I would rename this variable $is_valid_username 
// so it's more obvious what you're doing

JavaScript:

$.post( base_url+'cms-profile/profile_ajax/valid_username/',
  { username : $("#username").val() }, 
  function( data ) {
    return $.parseJSON( data );
  }
});