Friday, April 15, 2011

Invoking AJAX call from Grails

Usecase:
Need to populate second drop down values based on the selected first drop down value.
In this example let us discuss about populating the available applications on a selected server.

Implementation:
* In your main .gsp page, associate an id to the first select drop down(i.e. server drop down). The code snippet displays the list of server via domain class Server.groovy.

<g:select>
from="${Server.list()}"
id="serverSelect" noSelection="['':'-- Select Server --']"
name="selectedServer" value="${domainInstance?.selectedServer}"
optionKey="name" optionValue="name">
</g:select>


* Wrap the second select drop down (i.e. Application list) into a div tag.

<div id="appversion_select" >
<g:select from="${domainInstance?.applications}"
name="appVersion" value="${domainInstance?.selectedApplication}">
</g:select>
</div>

* Add the required javascript function invoke AJAX call to backed controller. Follow in line comments..

//This script listens to a change in the value of the select drop donw bearing an id as 'serverSelect'
document.observe('dom:loaded', function() {
$("serverSelect").observe("change", respondToServerSelect);
});

function respondToServerSelect(event)
{
//It inovkes the associated controller with selectedServer as parameter and updated the response in a
//bearing id as 'appversion_select'

new Ajax.Updater("appversion_select",

"/server/getAppsFromServer",

{method:'get', parameters: {

selectedServer : $F("selectedServer")
}
}
);
}


* Add a GSP matching the return view of the getAppFromServer method from the controller, default you can create getAppsFromServer.gsp with following code. This same as second dropdown code.

<g:select from="${domainInstance?.applications}"
name="appVersion" value="${domainInstance?.selectedApplication}">
</g:select>

* Controller code: Here is the closure required in the controller class

def getAppsFromServer = {
println ("Retrieve the application from the server")

def existingApps = new ArrayList()

// invoke the business service to get the applications.
domainInstance.appVersions = existingApps
return [domainInstance: domainInstance]
}


Once you cover all of them, now you should be able to populate the application list based on the selected server.

Appreciate your comments.....

No comments: