Ajax not working with Chain drop Down
Grails 2 uses jQuery as its default javascript library, stick with jQuery and the already present functions in Grails and you'll soon be Ajax'ifying your apps.
Check out the Grails tags such as remoteFunction
http://grails.org/doc/latest/ref/Tags/remoteFunction.html to see how you can very easily trigger an an Ajax call and update a portion of your webpage.
Has any one been able to make
http://grails.org/AJAX-Driven+SELECTs+in+GSP Country City dropDown to work for grails 2.0.3?
I have added the submit button cntDrop.gsp because , I could not update the city dropdown by changing the country drop down by ajax. But if I click the
submit button after changing the country drop down, then city drop down is update. What do i need to do to make the ajax work without a
submit button? I am just usiing the default jquery for grails 2.0.3.
CountryController:
package cc
import grails.converters.*
class CountryController {
def scaffold = cc.Country
def cntDrop = {
[countryList: Country.list(params)]
}
def ajaxGetCities = {
def country = Country.get(params.cntName)
//render(template: 'countrySelection', model: [r:country])
render(view: 'cntDrop', model: [c:country?.cities])
//render country?.cities as JSON
//render"my ${params?.cntName} ' ' ${country?.name} country"
}
}
cntDrop.gsp:
<html>
<head>
<g:javascript src="myjs.js" />
<g:javascript library="jquery" />
<r:layoutResources/>
</head>
<body>
<g:form method="post" >
<g:select
name="cntName"
from="${cc.Country.list()}"
noSelection="['':'Choose country']"
optionKey="id"
optionValue="name"
value="${country?.id}"
onchange="${remoteFunction(
controller:'Country',
action:'ajaxGetCities',
params:'\'country.id=\' + escape(this.value)',
onSuccess: 'updateCity(e)'
)}"
/>
</br>
</br>
<fieldset class="buttons">
<g:actionSubmit class="save" action="ajaxGetCities" value="${message(code: 'default.button.cnt.label', default: 'drop')}" />
</fieldset>
</br>
</br>
<g:select name="city"
from="${c}"
optionKey="id"
id="city.name"/>
</g:form>
</body>
</html>
myjs.js file:
//<g:javascript>
function updateCity(e) {
// The response comes back as a bunch-o-JSON
var cities = eval("(" + e.responseText + ")") // evaluate JSON
if (cities) {
var rselect = document.getElementById('city') // Clear all previous options
var l = rselect.length
while (l > 0) {
l--
rselect.remove(l)
} // Rebuild the select
for (var i=0; i < cities.length; i++) {
var city = cities
var opt = document.createElement('option');
opt.text = city.name
opt.value = city.id
try {
rselect.add(opt, null) // standards compliant; doesn't work in IE
}
catch(ex) {
rselect.add(opt) // IE only
}
}
}
}
// This is called when the page loads to initialize city
var zselect = document.getElementById('country.name')
var zopt = zselect.options[zselect.selectedIndex]
${remoteFunction(controller:"country", action:"ajaxGetCities", params:"'id=' + zopt.value", onComplete:"updateCity(e)")}
//</g:javascript>
grailsgk