always return false in livevalidation

236 Views Asked by At

I have no way to catch if the ajax request is true or false using livevalidation.js. It always return username whatever the php function executes to either false or true;

PHP Code

public function valid_username()
{
   $is_username_exist = 'some query here';

   if($is_username_exist == true){
        $output['success'] = true;
   }else{
       $output['success'] = false;
   }

   echo json_encode($output);
}

JS Code

$(document).ready( function() {
var username = new LiveValidation('username',{validMessage: 'Available', wait:500});
username.add( Validate.Presence );
username.add( Validate.Length, { minimum: 4, maximum: 10 } );
username.add( Validate.Custom, { against: function() { return  check_username_availability( 'username', '#username', base_url+'cms-profile/profile_ajax/valid_username');}, failureMessage: 'Username already taken' } );

});

function check_username_availability(name, id, postUrl)
{
var dataVal = name+'='+$(id).val();

  $.ajax({
    url: postUrl,
    cache: false,
    type: 'post',
    dataType: 'json',
    data: dataVal,
    async:  false,
    success: function(data) {
     return $.parseJSON(data);
    }
  });  
}
1

There are 1 best solutions below

1
On

When you POSTing with ajax set data as this way:

$.ajax({
    url: postUrl,
    cache: false,
    type: 'post',
    dataType: 'json',
    data: {'name':name , 'id': id},
    async:  false,
    success: function(data) {
     return data.success;
    }
  });  

And dont use parseJSON. There is no need as you can directly return your responde value..