Java Developer

Grails AJAX tutorial - remoteLink tag

Grails is a very nice platform to program AJAX applications. It supports the feature out of the box. The API is very simple and easy to grasp where you only need to learn the 5 basic tags:

  • remoteLink - create an AJAX based link
  • remoteFunction - create a javascript code that fires an AJAX request
  • remoteField - creates a text control field that fires an AJAX request when the value changes
  • formRemote and submitToRemote - tags to make a form serialize it's values and submit using an AJAX request.
In my experience, I have created several paid projects in the past that only use these 5 tags to make a rich user experience. It is more than enough for the purpose.
For this part of the tutorial, the focus will be on the tag remoteLink. The basic usage of this tag looks like:
<g:remoteLink controller="simple" action="renderString" update="mainContent">Render String</g:remoteLink>
The key concept here is that the controller and action fields will determine which code to invoke. That action can then render the content, that will be placed inside the element (innerHTML) defined in the field update.
Below is a sample application to serve as an example. It is a simple menu system where the left side bar contains the menu links, while the right side will hold the content article. The finished application should look like this:

Below is the complete code of the application. We will explain each part later

SimpleController.groovy

package tutorial
class SimpleController {
    def sideMenu() { }
    def renderString() {
        render "Hello, this is a rendered string."
    }
    def renderPage() {
    }
    def renderView() {
        render (view:'renderView')
    }
    def renderTemplate() {
        render (template: 'renderTemplate')
    }
    def withIdParam() {
        def id = params.id
        render "The ID given is ${id}"
    }
    def withCustomParam() {
        def a = params.a.toInteger()
        def b = params.b.toInteger()
        render "${a} + ${b} = ${a+b}"
    }
}

views/simple/sideMenu.gsp

<!DOCTYPE html>
<html>
	<head>
		<meta name="layout" content="main"/>
		<title>Simple Ajax</title>
        <g:javascript library="jquery"/>
	</head>
	<body>
        <div style='float: left; width: 20%; min-height: 500px; background-color: #c0c0c0;'>
            <g:set var="theID" value="${999}"/>
            <g:set var="firstNumber" value="${5}"/>
            <g:set var="secondNumber" value="${7}"/>
            <g:remoteLink controller="simple" action="renderString"
                update="mainContent">Render String</g:remoteLink><br/>
            <g:remoteLink controller="simple" action="renderPage"
                update="mainContent">Render Page</g:remoteLink><br/>
            <g:remoteLink controller="simple" action="renderView"
                update="mainContent">Render View</g:remoteLink><br/>
            <g:remoteLink controller="simple" action="renderTemplate"
                update="mainContent">Render Template</g:remoteLink><br/>
            <g:remoteLink controller="simple" action="withIdParam" id="${theID}"
                update="mainContent">With ID Parameter</g:remoteLink><br/>
            <g:remoteLink controller="simple" action="withCustomParam"
                params="${[a:firstNumber, b:secondNumber]}"
                update="mainContent">With Custom Parameter</g:remoteLink><br/>
        </div>
        <div id="mainContent" style='float: right; width: 80%; min-height: 500px; background-color: #c0ffc0;'>
            <p>This is the main content</p>
        </div>
	</body>
</html>

views/simple/renderPage.gsp

<h3>This is a sample page</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p>

views/simple/renderView.gsp

<h3>This is a sample view</h3>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>

views/simple/_renderTemplate.gsp

<h3>This is a sample template</h3>
<p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p>


SIMPLE USAGE
<g:remoteLink controller="simple" action="renderString"
                update="mainContent">Render String</g:remoteLink><br/>
This is the simplest form where we specified which controller action to invoke, and which HTML element to update. When the link is clicked, the AJAX request will invoke SimpleController's renderString. The action will render the string "Hello, this is a rendered string.".
        <div id="mainContent" style='float: right; width: 80%; min-height: 500px; background-color: #c0ffc0;'>
            <p>This is the main content</p>
        </div>
Since the code says to update mainContent, it's innerHTML will be replaced by the result of the controller's action. The output then will look like:

SAMPLE WAYS TO RENDER CONTENT
The next three links calls the actions renderPage, renderView, and renderTemplate. These are just example on different ways of rendering the result. The sample output:



PASSING PARAMETERS
The sample below invokes withIdParam and withCustomParam actions. These are samples on how to pass parameters from your GSP to the controller:

<g:set var="theID" value="${999}"/>
<g:set var="firstNumber" value="${5}"/>
<g:set var="secondNumber" value="${7}"/>
<g:remoteLink controller="simple" action="withIdParam" id="${theID}"
    update="mainContent">With ID Parameter</g:remoteLink><br/>
<g:remoteLink controller="simple" action="withCustomParam"
    params="${[a:firstNumber, b:secondNumber]}"
    update="mainContent">With Custom Parameter</g:remoteLink><br/>

which is very straightforward.
def withIdParam() {
    def id = params.id
    render "The ID given is ${id}"
}
def withCustomParam() {
    def a = params.a.toInteger()
    def b = params.b.toInteger()
    render "${a} + ${b} = ${a+b}"
}
The output are:


NOTES
As shown above, this tag is very easy to learn. It is easy to pickup even for AJAX beginners. Yet this tag, together with the other 4 default AJAX tags of Grails, are enough to create very cool applications.
You can checkout the source code for this example here or download the zip file here.
List of Grails AJAX Tutorials

Tags: ajax, grails, remoteLink, tag