Java Developer

Grails AJAX tutorial - remoteFunction tag

The tag remoteFunction is one of the most powerful tag in Grails. Because of it's simplicity and flexibility, you can use it as building block for building complex interface behavior. Check out also my post on remoteLink tag as they share many similarities.
Here is a comple sample application demonstrating many ways of using this tag.

GreetingController.groovy

package tutorial
class GreetingController {
    def index() {}
    def initialGreeting() {
        render "Hello this is a greeting box."
    }
    static int counter = 0
    def count() {
        counter ++
        render "The current number now is ${counter}"
    }
    def greetName() {
        render "Hello there ${params.name}"
    }
}

index.gsp

<!DOCTYPE html>
<html>
	<head>
		<meta name="layout" content="main"/>
		<title>Simple Ajax</title>
        <g:javascript library="jquery"/>
        <style>
            #greetingBox {
                border: 1px solid #000; width: 300px; height: 100px; background-color: #c0c0c0;
            }
        </style>
	</head>
	<body>
        <div id="greetingBox">
        </div>
        <div>
            <button onclick="<g:remoteFunction controller="greeting" action="count" update="greetingBox"/>">Count</button>
        </div>
        <div>
            <input type="text" name="name" onchange="greetName(this.value)"/>
        </div>
        <script>
            <g:remoteFunction controller="greeting" action="initialGreeting" update="greetingBox"/>

function greetName(name) { <g:remoteFunction controller="greeting" action="greetName" update="greetingBox" params="'name='+name"/> } </script> </body> </html>

As you could see, it is very similar to remoteLink. The basic parameters are controller, action and update attributes. Where it define which controller code to invoke, and which HTML element to update.
<g:remoteFunction controller="greeting" action="initialGreeting" update="greetingBox"/>
This will invoke the initialGreeting action of GreetingController, and place the rendered contents inside greetingBox element.

If you will check out the source, it looks like this

jQuery.ajax({type:'POST', url:'/grails-sample-ajax/greeting/initialGreeting',success:function(data,textStatus){jQuery('#greetingBox').html(data);},error:function(XMLHttpRequest,textStatus,errorThrown){}});

As you could see, this is just an ordinary javascript code that uses JQuery. And you can invoke it anywhere:
INVOKE ANYWHERE INSIDE SCRIPT TAG
<script>
    <g:remoteFunction controller="greeting" action="initialGreeting" update="greetingBox"/>
This will get invoked right away when the Javascript engine parses it. When the sample page above is loaded, the initialGreeting will be invoked right away, producing the output:

DECLARE IN CONTROL'S EVENTS
<button onclick="<g:remoteFunction controller="greeting" action="count" update="greetingBox"/>">Count</button>
This will make an AJAX request every time the button is clicked.

USE INSIDE CUSTOM FUNCTIONS
<input type="text" name="name" onchange="greetName(this.value)"/>
<script>
    function greetName(name) {
        <g:remoteFunction controller="greeting" action="greetName" update="greetingBox" params="'name='+name"/>
    }
</script>
This is my favorite where you place it inside functions, and reuse it all through out your page.

PASSING PARAMETERS
It is also easy to pass parameter from javascript to your controller. Sample below for passing parameter name:

var theName = 'Peter'
<g:remoteFunction controller="greeting" action="greetName" update="greetingBox" params="'name='+theName"/>

NOTES
This is tag I used the most when I am building my own AJAX application. It's so simple yet very powerful. In fact the remoteLink and remoteField tags can be emulated using this. If you will just be imaginative, there's no limit on what you can do!
You can checkout the source code for this example here or download the zip file here.
List of Grails AJAX Tutorials

Tags: ajax, grails, remoteFunction, tag