Monday, October 19, 2009

Simple Ajax sample

Using Ajax in Grails is quite simple. Grails have the prototype library making it easy to use Ajax in Grails.

You can try it out by creating a Grails-project. Here is an example ant some explanation of what is nescessary to think of.

1. Create a grails project:
2. Create a controller:

3. Create 2 .gsp-files in the /views/ajax folder; index.gsp and _itemList.gsp (_ means that it is a template)

4. Change the /views/layout/main.gsp by adding the following row

5. In the index.gsp in your ajax folder, put in this code:

6. In your _itemList.gsp put this code:

7. Now the only thing we need is some code in the controller. Open the AjaxController and put this code:

So what makes this work?

First of all, Grails supply the tags submitToRemote which is used for the "Add" button and remoteLink which is used for the "remove" link. These are used to use Ajax from grails and the only thing needed to make them work is to include the "prototype" javascript library, which we did in the layout to make it available on all pages. If you look on these tags you see the property action="" and update="listItems" this properties tells the framework what action to call and what to do with the result when the action is finished. Look at the index.gsp and you will see a <div> with the id="listItems", if you remember this is the same id that you saw as text in the update-property, this i the glue between the action pointed out and where to put the result. Pretty easy and straightforward, to make it short you need this
  1. Add prototype JavaScript library to the layout
  2. Add a DIV for the result
  3. Add some remote call and point it to the action you want to happen and where to put the result
Note : Ajax is used for enhanced functionality and to not to have to reload pages. Therefor using templates with small fragments of code is a convenient way to reuse code-blocks and functionality. It is better to think a bit ahead of what is needed to make nice solutions and reuse of code.