Pass JSON using java servlet to populate the simple Column chart

812 views
Skip to first unread message

George Rosario

unread,
Aug 6, 2014, 1:24:28 AM8/6/14
to google-visua...@googlegroups.com
Hi. I am new to google charts , I am building a simple application which takes data from mysql database into a servlet and forms a JSON object , Which is passed to XHTML file where i want to display a coloum chart using that JSON object. I am able to create a JSON object in java. But i dont know how to send the JSON object from servlet to XHTML and use that object to generate the chart , Can anybody help?  
Thanks in ADVANCE....

Andrew Gallant

unread,
Aug 6, 2014, 8:54:00 AM8/6/14
to google-visua...@googlegroups.com
There are two approaches you can take with this: either insert your data into the page server-side, or use an AJAX request client-side to dynamically fetch the data.

Since you already have a servlet that serves up a JSON object, using AJAX should be simple enough.  I recommend using a javascript library like jQuery or Mootools (whatever works best for you) to handle the AJAX work, since writing AJAX in plain javascript can be a bit of a pain.  Here's an example using jQuery:

function drawChart() {
    $.ajax({
        url: '/path/to/servlet',
        dataType: 'json',
        data: {
            // key: value pairs for whatever data you need to send to the server, if any
        },
        success: function (json) {
            // assumes json is a DataTable-compatible JSON string
            var data = new google.visualization.DataTable(json);
            var chart = new google.visualization.ColumnChart(document.querySelector('#chart_div'));
            chart.draw(data, {
                // chart options
                height: 400,
                width: 600
            });
        }
    });
}
google.load('visualization', '1', { 'packages': ['corechart'], callback: drawChart}); 

This example draws a ColumnChart in a div with the id "chart_div".  It assumes that your JSON is in the correct format for the Visualization API to use; if your data is in a different format, then you either need to change the JSON format, or you need to parse the JSON into a DataTable manually in javascript.  If you post an example of the JSON your servlet creates, I can help you with either approach.

George Rosario

unread,
Aug 6, 2014, 1:49:52 PM8/6/14
to google-visua...@googlegroups.com
Thanks Andrew....
Reply all
Reply to author
Forward
0 new messages