Monday, August 1, 2011

Grails jQuery Ajax Autocomplete with jQuery-UI

Download Grails application framework for http://www.grails.org

Create grails application.

Download and install jQuery from (http://www.jquery.com) (copy the JavaScript files to your grails app home web-app/js folder)

Download and install jQuery ui plugin

Create a domain class "City"

package myapp
class City {
    String city
    static constraints = {
        city nullable:false, blank:false, maxSize:200
    }
}

create controller
grails create-controller city
edit the CityController,
import grails.converters.*
add
def ajaxCityFinder = {
   def citiesFound = City.withCriteria {
         ilike 'city', params.term + '%'
        }
 render (citiesFound as JSON)
}

Update your gsp file with the following code:
<html>
    <head>
        <meta name="layout" content="main" />

        <link rel="stylesheet" href="${resource(dir:'css/smoothness',file:'jquery-ui-1.8.14.custom.css')}" />

        <g:javascript library="jquery.min" />
        <g:javascript library="jquery-ui-1.8.14.custom.min" />
        <g:javascript>
            $(document).ready(function() {
               $('#city').autocomplete({
                 source: '<g:createLink controller='city' action='ajaxCityFinder'/>'
               });
               
            });       
        </g:javascript>
    </head>
    <body>
        <div class="demo">
            <div class="ui-widget">
                <label for="city">City: </label>
                <input id="city">
            </div>
        </div>
    </body>
</html>



it may work!!!
Source at  https://github.com/miserableme/myAjaxExperiments.git