content top

chart sample as a js lib via jsni

The previous post showed a GWT module that would select data from xml via xpath4js and then render a GWT visualization. That post was designed to show the xpath side of things in action, rather than show a useful way to incorporate google charts into a web site… Today I thought that it would be good to show the web page calling Google’s chart api on demand, passing in the path for the source xml file and the id of the target element for the chart. SO…

normal js inside the html page

<script type="text/javascript">

       function loadCharts(){
            try{
                 doChart("chartinput.xml","divChart");
                 doChart("chartinput2.xml","divChart2");
                 doChart("chartinput3.xml","divChart3");
            }
            catch(err){
                 setTimeout("loadCharts()",1000);
            }
       }
</script>

calls the GWT compiled js to do this…




IE woes: The first version of this example worked on FF and Chrome with no problems, however in IE the charts failed to load on the browser re-fresh. In pinned the problem down to a caching of the js for Google’s ajax loader API (which loads up the scripts used to render the charts). As a quick fix for this I injected the js that calls the ajax into the lib’s onModuleLoad() method with a random value appended to the end of the query string so that the file will be fetched fresh each time (this is a hack, so please do let me know if you know of a better solution). The injection code was directly from google’s wrapper for the loader…

    public void onModuleLoad() {
        // ** need to stop IE from caching ajax loader script,
        //      otherwise will not load on refresh (fubar)
        Document doc = Document.get();
        String src = "http://www.google.com/jsapi?"+
                         "callback=__gwt_AjaxLoader_onLoad" +
                         "&x=" + ((int)(Math.random()*100));
        ScriptElement script = doc.createScriptElement();
        script.setSrc(src);
        script.setType("text/javascript");
        doc.getBody().appendChild(script);
        // end fubar**

        publish();
    }

The source for this project (in eclipse) can be found here:

https://code.google.com/p/xpath4js/source/browse/#svn/trunk/samples/googleChartSampleLib

happy coding :)
Pete



Leave a Reply

You must be logged in to post a comment.