Furkan Taşkale
Furkan Taşkale

Reputation: 23

Filling Google Chart with Ajax from a database

Im trying to get a google bar chart to get two values from a simple database and display in the graph. I can display the values from an array but when I try to get the data from database using ajax it would not get the values.(I was able to print the values in the index).

Note: Hey there I'm trying to get familiar with javascript and use google charts. I looked up almost everything that i can find still i could not solve my problem. This is my very first question to stackoverflow. Please help.

Ive got a simple database which only holds 4 values representing cashIn and cashOut of a company over 12 months.

I created a MVC web application then added the database to it. Here is the controller class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            DenemeDataEntities db= new DenemeDataEntities();

            List<GelirGider > gelirList = db.GelirGiders.ToList();
            Array gelirArray = db.GelirGiders.ToArray();

            //return Json(gelirList, JsonRequestBehavior.AllowGet);
            //return Json(gelirList, JsonRequestBehavior.AllowGet);
            return View(gelirList);
        }

        public ActionResult Index2()
        {
            DenemeDataEntities db = new DenemeDataEntities();

            List<GelirGider> gelirList = db.GelirGiders.ToList();
            //Array gelirArray = db.GelirGiders.ToArray();


           return Json(gelirList, JsonRequestBehavior.AllowGet);
            //return View(gelirList);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

And here is the Index view class

@{
    ViewBag.Title = "Home Page";
}
@using WebApplication2.Models;
@model List<GelirGider>



<html>
<head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

        // Load the Visualization API and the corechart package.
        google.charts.load('current', { 'packages': ['corechart'] });

        // Set a callback to run when the Google Visualization API is loaded.
        google.charts.setOnLoadCallback(drawChart);

        // Callback that creates and populates a data table,
        // instantiates the pie chart, passes in the data and
        // draws it.
        function drawChart() {

            // Create the data table.
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Ay');
            data.addColumn('number', 'Gelir');
           

            $.ajax({
                url: '/Home/Index2',
                type: 'POST',
                dataType: 'json',
                success: function (data) {
                    alert('asdasda');
                    var data = new google.visualization.DataTable();
                    data.addColumn('string', 'Ay');
                    data.addColumn('number', 'Gelir');
                    
                    $.each(data, function (i, item) {
                        data.addRows([ item.Ay ,item.Gelir])
                        //data.addRows(eval('[' + item.Ay + ', ' + item.Gelir ']'));
//                        data.addRows([ ['Mushrooms', 3], ]);
                    });
                    
             

                    // Set chart options
                    var options = {
                        'title': 'How Much Pizza I Ate Last Night',
                        'width': 400,
                        'height': 300
                    };

                    // Instantiate and draw our chart, passing in some options.
                    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
                    chart.draw(data, options);

                }

            });


         
        }
    </script>
</head>

<body>
    <!--Div that will hold the pie chart-->
    

    <div class="jumbotron">
        <h1>Gelir Gider Tablosu</h1>
        <button onclick="drawChart();">bilgileri goster</button>
    </div>
    <div id="chart_div"></div>
</body>
</html>

I believe this line can not take the data therefore could not put the data in to the chart. I tried some other combinations incase of an simple indentation mistake but again not worked data.addRows([ item.Ay ,item.Gelir])

Please help. I tried to be as clear as possible. Thanks in advance

Upvotes: 2

Views: 1558

Answers (1)

Monir Tarabishi
Monir Tarabishi

Reputation: 714

It seems that you have a couple of issues in your code:

  1. Using the same name for the Ajax response object and the google chart data object.
  2. Google Charts Datatable.AddRows() method receives an array of arrays object and doesn't accept a single array.
  3. Again you are using the newly created google chart datatable in the each statement

I've updated you Ajax code according to the previous points:

            $.ajax({
                url: '/Home/Index2',
                type: 'POST',
                dataType: 'json',
                success: function (response) {
                    var data = new google.visualization.DataTable();
                    data.addColumn('string', 'Ay');
                    data.addColumn('number', 'Gelir');
                    var arr = [];
                    $.each(response, function (i, item) {
                        arr.push([ item.Ay ,item.Gelir]);
                    });
                    data.addRows(arr);
                    // Set chart options
                    var options = {
                        'title': 'How Much Pizza I Ate Last Night',
                        'width': 400,
                        'height': 300
                    };
                    // Instantiate and draw our chart, passing in some options.
                    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
                    chart.draw(data, options);
                }
            });

Upvotes: 1

Related Questions