Convert string into parameter for arrayToDataTable (varString)

2

Hello, I'm starting to use ajax and the Google API (chart) to create charts.

I use a Generic Handler that I called 'EmployeesCompany.ashx', in it I make a query in the database and return a string in this way;

context.Response.Write(valores.ToString());

The data I get comes to Ajax as a string (in the correct format of the parameter I'm supposed to pass) as follows;


Myquestion:'IsitpossibletoconvertthisstringtoavalidarrayorparameterformyGoogleAPIcalltowork?'becauseofthewayitisnowIgetanerrormessagesaying:'JavaScriptruntimeerror:Notanarray'HomeAjaxFunction:

< script type = "text/javascript" >
  google.load("visualization", "1", {
    packages: ["corechart"]
  });
$(document).ready(function() {
  var urlH = "GenericHandler/ColaboradoresEmpresa.ashx";
  $.ajax({
    url: urlH,
    type: "POST",
    data: {},
    async: true,
    success: function(Valores) {
      alert(Valores);
      var data = google.visualization.arrayToDataTable(Valores);
      var options = {
        title: '',
        is3D: false
      };
      var chart = new google.visualization.PieChart(document.getElementById('Empresa'));
      chart.draw(data, options);
    },
    error: function(data) {
      alert("ERRO: " + data.status);
    },
    timeout: 15000
  });
}); < /script>


Code of the .ASHX files that returns the string pro Ajax;

public void ProcessRequest(HttpContext context)
        {
            SqlCommand comando = new SqlCommand();
            comando.Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["NOMEDB"].ConnectionString);
            comando.CommandText = "SELECT/CONSULTA NO BANCO DE DADOS";
            comando.Connection.Open();
            string valores = "[['Empresa_', 'Colaboradores'], ";
            SqlDataReader dr = comando.ExecuteReader();
            while (dr.Read())
            {
                if (dr["NOMEFANTASIA"] != DBNull.Value)
                {
                    valores += "['" + dr["NOMEFANTASIA"].ToString() + "',";
                }
                if (dr["QTD"] != DBNull.Value)
                {
                    valores += dr["QTD"].ToString() + "],";
                }
            }
            if (valores.Length > 0)
            {
                valores = valores.Substring(0, valores.Length - 1) + ", ]";
            }
            comando.Connection.Close();
            context.Response.Write(valores.ToString());
        }
    
asked by anonymous 13.11.2014 / 12:55

1 answer

1

I made a test using these links and I was able to use Generic Handler using this library

link

and the code available in the google chart docs ( link )

another answer: link

Aspx Code

<head runat="server">
<title>Teste Google Chart</title>

<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script><scripttype="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">

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

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

function drawChart() {
  var jsonData = $.ajax({
      url: "chartData.ashx",
      dataType:"json",
      async: false
      }).responseText;

  // Create our data table out of JSON data loaded from server.
  var data = new google.visualization.DataTable(jsonData);

  // Instantiate and draw our chart, passing in some options.
  var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 400, height: 240});
}

</script>

                                     

ashx code

using Google.DataTable.Net.Wrapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TesteGoogleChart
{
    /// 
    /// Summary description for chartData
    /// 
    public class chartData : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";

            List funcs = new List();

            funcs.Add(new Funcioanrios { Nome = "Araujo", Salario = 550 });
            funcs.Add(new Funcioanrios { Nome = "Araujo a", Salario = 500 });
            funcs.Add(new Funcioanrios { Nome = "Araujo b", Salario = 400 });
            funcs.Add(new Funcioanrios { Nome = "Araujo c", Salario = 350 });
            funcs.Add(new Funcioanrios { Nome = "Araujo d", Salario = 300 });
            funcs.Add(new Funcioanrios { Nome = "Araujo e", Salario = 250 });

            var dt = new Google.DataTable.Net.Wrapper.DataTable();
            dt.AddColumn(new Column(ColumnType.String, "Nome", "Nome"));
            dt.AddColumn(new Column(ColumnType.Number, "Salario", "Salario"));

            foreach (var item in funcs)
            {
                Row r = dt.NewRow();
                r.AddCellRange(new Cell[]
                {
                    new Cell(item.Nome),
                    new Cell(item.Salario)
                });
                dt.AddRow(r);
            }

            //Let's create a Json string as expected by the Google Charts API.
            context.Response.Write(dt.GetJson());

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }


    public class Funcioanrios
    {
        public string Nome { get; set; }
        public decimal Salario { get; set; }
    }

}
    
14.11.2014 / 12:54