Pages

Sunday, February 22, 2015

grails auto refresh a div with jquery

I guess the toughest dead end i had so far - i needed to refresh only a part of a page, one div, every 10 seconds, for example. I had completely no idea how to solve it. After some time and no responses on SO i thought that i probably needed to create a separate view and point the div to this view with jquery, something like that. 
The solution turned out to be almost like i thought.
I've solved this with help of joshm76 from #grails on freenode.
There are several steps for this solution:
  1. i need a template with the div contents i need to update
  2. i need a controller that with a model passes needed values to the template
  3. i need to include this inside the div i want to update with a 
  4. with jquery i update the div contents
1) Template is a .gsp file with _ before the name, like _myTemplate.gsp. Put it in the view folder of the controller you will be using.
2)
    def action(){
    def var
    //some logic to populate the variable

    Map model = [myVar: var]
    render(template: '_myTemplate', model: model)
}
in the template the variable can be accessed with ${myVar}
3) inside the div you need to update, put the <g:include> instead of the content you had there before (now the content is in the template)
<g:include controller='controller' action='action' />
4) the jquery part (fetches the template every 5 seconds):
    $(document).ready(
            function() {
                setInterval(function() { 
                $('#divId').load('/app/controller/action');
                }, 5000);
            });
you can also use the $.get() function, the result seems to be identical

No comments:

Post a Comment