Friday, 1 May 2009

Kohana Ajax Username Availability

I'm trying out some simple exercises with the Kohana framework. I want to make a website that has a really swish user experience. This exercise creates a user interface where new users will be told if the username they are entering in the registration form is available or taken as they are typing it. I'll be using Jquery as it allows for the functionality I want with a very minimal amount of code. Here's the Kohana controller code that checks to see whether a username is taken and returns a simple JSON response.
class Ajax_Controller extends Controller{

  public function checkUserName($username="")
  {
   $user = ORM::factory('user', $username);
   $msg = "<div class='good_feedback'>Available</div>";
   $disable = false;
   if ($user->loaded)
   {
       $msg = "<div class='bad_feedback'>Username Taken</div>";
       $disable = true;
   }
   echo json_encode(array('message' => $msg, 'disable' => $disable));
  }
}
The javascript in the html attaches a handler function to the keyup event on the username field so whenever the username changes the ajax request is created and then processed updating a feedback div and enabling or disabling the submit button.
$(document).ready(function() {
// do stuff when DOM is ready
$("#username").keyup(function() {
 jQuery.getJSON('/kohana/index.php/ajax/checkUserName/' + $(this).val(),
   function( json ) {
     $("#username_feedback").html( json.message );
     $("#submit").attr('disabled', json.disable  );
    }
 );
});
});
And the HTML isn't very complicated:
Username: 
<?php print form::input('username'); ?>
<div id="'username_feedback'"></div>