One issue you have here is how you are embedding your $user variable into your sql query. Without focusing on the obvious SQL injection risk you are putting yourself in with this approach you also have a syntax error:
$query = "Select a.username FROM #__users where username = '$user' ";
should be
$query = 'Select a.username FROM #__users where username = "' **. $user .** '" ';
But you should do something like this instead to prevent from an SQL injection attack.
Another issue is how you are calling your backend validation function. You haev to user Joomla's component url structure to point to a function you have defined in your controller and pointed to in your router.php. Your controller function will look somethin like:
function username_validate() {
$app = JFactory::getApplication(); // this allows you to
$requestedUsername = JRequest::getVar("username", null);
$query = "Select COUNT(username) FROM #__users where username = ' . $requestedUsername . ' ";
$db =& JFactory::getDBO();
$result = $db->setQuery($query);
$available = mysql_num_rows($result);
echo = $available > = ? "true" : "false";
$app->close();
}
and the URL to call it will look something like this:
'index.php?option=com_mycomponent&task=username_validate&username=' + user
where com_mycomponent is the name of your component.
Ok so continuing on, here is a very simple example of how to validate your username field on the fly: Username Validation. For this example to work for you you would have to substitute the static array for an AJAX call that returns a list of all usernames but this is not very clever or secure. A better approach is to fire your user input off to be checked and to return a response as you have attempted in you example.
Using your approach you JS will look something like this:
$(document).ready(function() {
$("#username").keyup(function() {
var user = $(this).val();
$.ajax({
url: 'index.php?option=com_mycomponent&task=username_validate&username=' + user,
dataType: 'text',
success:function(responseText, statusText) {
if($(this).val().length == 0) {
$("#validationTxt").css("display", "none");
return false;
}
if(responseText == "false"){
$("#validationTxt").text("Username Already Taken");
$("#validationTxt").css({'color' : 'red', 'display' : 'block'});
} else {
$("#validationTxt").text("Username OK");
$("#validationTxt").css({'color' : 'green', 'display' : 'block'});
}
}
});
});
});
Instead of using .keyup() you could bind the .blur() event which fires an AJAX call off to the validation function when the user click or tabs out of the username text field. This would reduce the number of calls you have to make to your backend. If you want the feedback as the user types then I would strongly recommend making an SQL call to retrieve all of you usernames and store them in the Joomla session temporarily so you can your validation checks against an array of Strings rather then make a new SQL call everytime the user types something in your text field.