5

I would like to use Google visualization charts for displaying information into a graph.

The javascript function for setting value into the graph looks like this:

function drawLineChart(chartType) {

    if(chartType == undefined) {
        chartType = 'data1';
    }

    var data = {
        data1: [
            ['Year', 'Sales', 'Expenses'],
            ['2004',  1000,      400],
            ['2005',  1170,      460],
            ['2006',  660,       1120],
            ['2007',  1030,      540]
        ]
    };

    ...
}

My problem is, that I don't know how to fill out array like this with values from database - any tip?

Thanks a lot

user984621
  • 46,344
  • 73
  • 224
  • 412

3 Answers3

4

You will need to embed the javascript in erb. If you name your file chart.js.erb, you will then be able to access Model logic from the javascript through erb. The downside to this method is that the javascript will have to be compiled on every page view, rather then being a statically compiled asset. This can slow down page load time, and an alternative route should be sought if this will be a heavily trafficked page.

Example

chart.js.erb

function drawLineChart(chartType) {

  if(chartType == undefined) {
    chartType = 'data1';
  }

  var data = {
    data1: [
      <%= Model.all.map { |m| [m.year, m.sales, m.expenses] }.unshift(['Year', 'Sales', 'Expenses']) %>
    ]
  };

  ...
}

Alternatively, you could create an AJAX request that populates the array on page load through an API controller. This method would allow the asset to be statically compiled, but is a bit more complex.

Eugene
  • 4,829
  • 1
  • 24
  • 49
2

You can use 'data' attribute:

# statistics.js.coffee
jQuery ->
  data = {
    labels : $("#orders_chart").data('dates'),
    datasets : [
      {
        fillColor : "rgba(220,220,220,0.5)",
        strokeColor : "rgba(220,220,220,1)",
        pointColor : "rgba(220,220,220,1)",
        pointStrokeColor : "#fff",
        data : $("#orders_chart").data('orders')
    }
  ]
}

ordersChart = new Chart($("#orders_chart").get(0).getContext("2d")).Line(data)

#statistics/index.html.erb
<%= content_tag 'canvas', '', id: 'orders_chart', width: '1000', height: '600', data: {orders: (Order.week_ago.map &:total), dates: (Order.week_ago.map &:created_at)} %>
ryaz
  • 316
  • 1
  • 8
0

This is what I did on my project 4 months ago. Pay very close attention to code. If you are using the ruby on rails, you can get data from controller by typing this <%= @get_data_from_controller_here %>

<html>
<head>
<title></title>
 <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart1);
       google.setOnLoadCallback(drawChart2);
      function drawChart1() {
        var data = google.visualization.arrayToDataTable([

          ['Work',     <%= @get_data_from_controller_here1 %>],
          ['Eat',      <%= @get_data_from_controller_here2 %>],
          ['Commute',  <%= @get_data_from_controller_here3 %>],
          ['Watch TV', <%= @get_data_from_controller_here4 %>],
          ['Sleep',    <%= @get_data_from_controller_here5 %>]
        ]);

        var options = {
          title: 'My Daily Activities',
          chartArea:{left:5, top:20,width:"100%",height:"100%"},
          height: 500,
          width: 500,
          is3D: true
        };

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

       function drawChart2() {
        var data = google.visualization.arrayToDataTable([

          ['Work',     <%= @get_data_from_controller_here11 %>],
          ['Eat',      <%= @get_data_from_controller_here22 %>],
          ['Commute',  <%= @get_data_from_controller_here33 %>],
          ['Watch TV', <%= @get_data_from_controller_here44 %>],
          ['Sleep',    <%= @get_data_from_controller_here55 %>]
        ]);

        var options = {
          title: 'My Daily Activities',
          chartArea:{left:5, top:20, width:"100%",height:"100%"},
          height: 500,
          width: 500,
          is3D: true
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d2'));
        chart.draw(data, options);
      }
    </script>

</head>
<body>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/redmond/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>


    <script type="text/javascript">
        $(document).ready(function () {

            $("#OpenDialog").click(function () {
                $('#dialog').css('overflow', 'hidden')
                $("#dialog").dialog({modal: true, 
                                    height: 450, 
                                    width: 850,
                                    resizable: true
                                    });
            });         
        });
    </script>

    <a id="OpenDialog" style="display:inline-block;" href="#" >Click here to open dialog</a>
    <div id="dialog" title="Dialog Title" style="display:none; overlay:hidden">
         <div id="piechart_3d1" style="width: 49%; height:49%; float:left;"></div>
         <div id="piechart_3d2" style="width: 49%; height:49%; float:right;"></div>
    </div>

</body>
jimagic
  • 4,045
  • 2
  • 28
  • 49