0
votes

I am working on a web application which retrieves JSON data from servlet and uses it to generate chart. I am successful in retrieving the requisite json file in Google Chart compliant JSON format but am unable to generate the chart.

The jsbin of google chart is in the foll link: http://jsbin.com/hofaqidape/1/watch?html,js,output

The data var should be generated using JSON and I am doing the following stuff in my servlet

response.setContentType("application/json");
            String json;
            newClass s =new newClass();
            List<newClass> classes = new ArrayList<newClass>();
            s.setCount(1);
            s.setName("Name");
            classes.add(s);
            s =new newClass();
            s.setCount(2);
            s.setName("Name1");
            classes.add(s);
            s =new newClass();
            s.setCount(3);
            s.setName("Name2");
            classes.add(s);
            s =new newClass();
            s.setCount(1);
            s.setName("Name4");
            classes.add(s);
            json="{ cols :[ {  label :  name  ,  type :  string },{ label :  count  ,  type :  number }], rows :[";
            String ss;int y;
            for(newClass class1:classes)
            {
                ss=class1.getName();
                y=class1.getCount();
                json+="{ c : [{ v : "+ss+" },{ v : "+y+"}]},";
            }
            json=json.substring(0, json.length()-1);
            json+="]}";
            JSONObject js=null;
            try {
                js = new JSONObject(json);
            } catch (ParseException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                out.print(js);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

on the html side I have the foll code for my chart generation:

$(document).ready(function(){
            $.ajax({
                    url : "Serv",
                    dataType: 'json',
                     contentType: 'application/json',
                    success : function(result) {
                          var dat=result;
                          alert(JSON.stringify(dat));
                          google.load('visualization', '1', {
                                packages: ['corechart', 'bar']
                            });
                            google.setOnLoadCallback(drawBasic);

                            function drawBasic() {

                                var data = new google.visualization.DataTable(dat);

                                var options = {
                                    title: 'Motivation Level Throughout the Day',
                                    hAxis: {
                                        title: 'Name'
                                    },
                                    vAxis: {
                                        title: 'Count'
                                    }
                                };

                                var chart = new google.visualization.ColumnChart(
                                document.getElementById('chart_div'));

                                chart.draw(data, options);
                            }

                    },
            complete: function()
            {
                alert('done');
            }
                });
        });

alert(JSON.stringify(dat)) gives the alert as

{"cols":[{"label":"name","type":"string"},{"label":"count","type":"number"}],"rows":[{"c":[{"v":"Name"},{"v":1}]},{"c":[{"v":"Name1"},{"v":2}]},{"c":[{"v":"Name2"},{"v":3}]},{"c":[{"v":"Name4"},{"v":1}]}]}

which is a valid JSON.

how do I generate the chart using this data just like I did in jsbin?

2
can you please tell why are you creating drawBasic() in success of ajax call? or to be more clear, why are you using everything in ajax call if it is set to execute on page load?? - Rohit416
this was supposed to happen on an event linked with a drop down selection. I removed a large part of the code and is basically left with the important stuff onle. anyhow I need an ajax call for servlet calling from jsp, right? - BeardAspirant
Okay that is cool, without messing with your requirements, i have however posted my response. See if that helps you.. - Rohit416

2 Answers

0
votes

google.setOnLoadCallback() set up a callback function to execute when Google Visualization API loaded, so google.load needs to load from the front explicitly. I am recalling it when i worked on them lately. My recommendation would be to move google.load and drawBasic() outside from AJAX call and use them in success of call, like this...

$(document).ready(function(){
    google.load('visualization', '1', {
        packages: ['corechart']
    });

    function drawBasic(d) {
      var data = new google.visualization.DataTable(d);
      var options = {
         title: 'Motivation Level Throughout the Day',
         hAxis: {
            title: 'Name'
         },
         vAxis: {
            title: 'Count'
         }
      };

      var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }

    $.ajax({
        url : "Serv",
        dataType: 'json',
         contentType: 'application/json',
        success : function(result) {
          google.setOnLoadCallback(drawBasic(JSON.stringify(result)));
        },
        complete: function(){
           // whatever..
        }
    });

 });

Update: You only need to specify packages: ['corechart'] which will define most basic charts, including the pie, bar, and column charts.

0
votes

finally got the answer to this question. removed google.setOnLoadCallback() and called drawBasic() function from ajax call itself. somehow setOnLoadCallback() and $(document).ready() doesnt seem to coexist.

working code:

<script>
google.load('visualization', '1', {
        packages: ['corechart']
    });

    function drawBasic(d) {
     var data = new google.visualization.DataTable(d);
      var options = {
         title: 'Sample Data',
         hAxis: {
            title: 'Name'
         },
         vAxis: {
            title: 'Count'
         },
         width: 600,
         height: 240
      };

      var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }  

                $(function(){
        $("#dd").change(function(){
            if($(this).val()!='null')
          {
                $.ajax({
            url : "Serv",
            data: {dd1:$(this).val()},
            dataType: 'json',
             contentType: 'application/json',
            success : function(result) {
              drawBasic(result);
            },
            complete: function(){
               // whatever..
            }
        })  ;
          }
            else
                {
                $("#chart_div").empty();
                alert('please select');
                }
        });
        });
    </script>