Search code examples
javascriptajaxgrailsgsp

grails refresh a google chart


I have a page X in my grails app which has a button to display a chart. It will call a controller with a domain object's id and the chart gets rendered in another page. Till here everything is clear to me.

However I have to reload the rendered chart page every 20 seconds. My website is a private one with few admin users only. So I decided to use simple javascript polling to do the refresh. This is the snippet in the chart gsp page that I want to reload every 20 seconds. Maybe using javascript setInterval.
<g:render id="chart" template="/building/${chartTemplate}" model="${model}"></g:render>

My controller requires a sensor id to be passed in when creating the chart, can I use the java script to do that? If so, how can I get it to the javascript function from the controller which initially redirected it here.

This is my GSP template which renders the chart.

<div id="linechart"></div>
<gvisualization:lineCoreChart dynamicLoading="${true}" elementId="linechart" title="${title}" 
 width="${750}" height="${450}" columns="${columns}" data="${data}"/>

Some weird javascript I have used, but not working.

<input type="text" id="sensorid" disabled="disabled" value="${sid }"/>
            <g:javascript>
                var int=self.setInterval("chart()",1000);
                var sensid;
                function chart(){
                    var d=new Date();
                    var t=d.toLocaleTimeString();
                    sensid = document.getElementById("sensorid").value;
                }
                ${remoteFunction(controller:"building", action:"createChart", params:"'sid=' + sensid")}
            </g:javascript>

Is there a way in which the javascript can reload the page. Full page reload is also fine. I have near zero knowledge of javascript so any help is highly appreciated.


Solution

  • Since you mention reloading the entire page is acceptable, then two easy ways would be:

    1) Include a META REFRESH tag in your GSP. Eg:

    <meta http-equiv="refresh" content="5">
    

    This is quite convenient, especially if you don't need to change the params (eg if the controller handles anything such as curent date/time used to update chart, etc).

    2) Either via Javascript "setTimeout" or a specific action, call a reload (or "history.go(0)", or "window.location.href=window.location.href").

    Eg for a button action to test it:

    <input type="button" value="Reload this page" onClick="window.location.reload();">
    

    or to do it automatically every 5 seconds, such as in this (extremely stripped down, so yes I've skipped things such as head, body and other tags..) HTML example:

    <script>
    setTimeout("window.location.reload()",5000);
    </script>
    
    Hello world.
    

    This gives you more control over exactly what you call, and could easily be modified to redirect to a different controller, same controller with new params, etc.