ajaxgrailsgrails-3.0.9

Simple AJAX example with Grails


I'm pretty new to Grails and I'm trying to learn how AJAX works in Grails. For this I'm trying to modify the multiply AJAX example from here so that my application displays the input string with AJAX on the page. (To clarify this: The user enters for example "foo" and the page should display "foo" under the search field)

This is my code so far:

My index.gsp template which contains an input form and shall display the string which is typed in the form:

<!doctype html>
<html>
<head>
</head>
<body>    
<div id="search">
    <g:render template="searchForm"/>
</div>
<div id="results">
    <g:render template="searchResultForm"/>
</div>
</body>
</html>

My _searchForm.gsp template which includes the search form:

<g:form>
    <label for="suchen"></label><g:textField name="suchen"/>
    <g:submitToRemote url="[controller:'search', action:'search']" update="results" value="Suchen"/>
</g:form>

My _searchResultForm.gsp template which shall display all results (in my case just the search string)

${results}

My SearchController which shall get the search string and return the same string:

class SearchController {

    ...

    def search(String s) {
        return s
    }
}

My problem is that after I write something into the input form and press the send button, nothing happens. No error but it also don't displays the input string under the input form.

You may wonder why I'm trying to do this with AJAX: My purpose is to realize an AJAX search. When the AJAX part works it shouldn't be a problem to add the search logic to the controller.


Solution

  • You should show your searchResultForm template. But I guess your problem is you don't send the model correctly to the gsp, and you haven't set the gsp in the response also

    If this is your template gsp:

    <div>${s}</div>
    

    You action have to be:

    def search(String s) {
            render template: 'searchResultForm', model:[s:s]
        }
    

    By this way, the action generates the html to be sent with the given model, which is rendered by jquery into the div.