Grails has some great built in ajax tags, but I prefer to use a javascript library directly (namely jquery)...
Download jquery and copy to web-app/js/jquery.js
In the head section of your form gsp or your layout add:
<g:javascript src="jquery.js"/>
In your form gsp I'd recommend adding an id attribute to your input field for username, makes it easier to reference an element by id:
<input type="text" name="username" id="username" value=""/>
In your controller method you can check your domain/service/etc to see if name is free. Below is a contrived example that returns the response as JSON, but you could also return html to fill a div, just depends on how you want to alert the user.
class UserController {
def checkAvailable = {
def available
if( User.findByUsername(params.id) ) {
available = false
} else {
available = true
}
response.contentType = "application/json"
render """{"available":${available}}"""
}
5, In your form gsp in the head section add
<script type="text/javascript">
// wait for dom to load
$(function(){
// set onblur event handler
$("#username").blur(function(){
// if some username was entered - this == #username
if($(this).length > 0) {
// use create link so we don't have to hardcode context
var url = "${createLink(controller:'user', action:'checkAvailable')}"
// async ajax request pass username entered as id parameter
$.getJSON(url, {id:$(this).val()}, function(json){
if(!json.available) {
// highlight field so user knows there's a problem
$("#username").css("border", "1px solid red");
// maybe throw up an alert box
alert("This username is taken");
// populate a hidden div on page and fill and display it..
$("#somehiddendiv").html("This ID is already taken").show();
}
});
}
});
});
</script>
Of course there are many ways to implement this, I just happen to prefer jquery over using some of the built-in ajaxy features.