How to create google charts from data comming from codebehind ?

In this tutorial I will show you that how can we create google column chart from data which will come from code behind.

first We need to get data into javascript of page, this can be done using jquery ajax like bellow

      $.ajax({
         type: "POST",
         url: "MyGoogleChart.aspx/GetGoogleChartData",
         success: function(data) {
            google.setOnLoadCallback(drawChart(data));
         },
         error: function () {
            alert("Some error occured while fetching data");
      }       
      });

Here I am calling WebMethod GetGoogleChartData of MyGoogleChart.aspx which is shown bellow

[WebMethod]
public static string GetGoogleChartData () 
{
   DataTable CharTable = new DataTable();
   CharTable.Columns.Add("ValueTitle");
   CharTable.Columns.Add("Value1");
   CharTable.Columns.Add("Value2");

   DataRow row = CharTable.NewRow();
   row[0] = "First Value";
   row[1] = 100
   row[2] = 200
   CharTable.Rows.Add(row);

   row = CharTable.NewRow();
   row[0] = "Second Value";
   row[1] = 300
   row[2] = 400
   CharTable.Rows.Add(row);

    return jsonChartData = new {
            chartdata = columnCharTable
         };
}

From this WebMethod I am returning data in the form of json string which will contain datatable.

So I will have json string returned to my jquery ajax request.

Note: As we know that we can also send data in request, so we can send parameters in ajax request & can get data as per our criteria.

Now we need to just format the data in the required form to use it for google column chart.

In ajax success function I am calling google.setOnLoadCallback(drawChart(data)); which render my column chart

Bellow is drawChart(data) function which creates data in required format & assign it to google column chart.

function drawChart(data)
{
   var chartData = new google.visualization.DataTable();
   chartData.addColumn('string', 'Value Title');
   chartData.addColumn('number', 'Value 1');
   chartData.addColumn('number', 'Value 2');

   for (var i = 0; i < data.chartData.length; i++)
      chartData .addRow([data.chartData[i].ValueTitle.toString(), parseInt(data.chartData[i].Value1), parseInt(data.chartData[i].Value2)]);

   var options = {
      title: "google Chart Data Demo",
      hAxis: {
         title: 'Values'
      },
      vAxis: {
         title: 'Value counts'
      },
      legend: {
         position: 'top',
      },
   };

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

Bellow is my HTML

<div id="columnchart_div" > </div>

admin