Convert string in parameter to arrayToDataTable(varString)

Asked

Viewed 718 times

2

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

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

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

The data I receive comes to Ajax as a string (in the correct format of the parameter I should pass) as follows;

inserir a descrição da imagem aqui

My question: 'Is it possible to convert this string to a valid array or parameter so that my call to the Google API works? 'cause the way it is now I get an error message saying: 'Javascript Runtime Error: Not an array'

Ajax function:

< 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>


File code . ASHX which 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());
        }
  • a question, the variable valores server-side, is an array?

  • @Enzotiezzi is a string in the format: "['Empresa_', 'Contributors'], ['Cleber', 27000], ['Jonathan', 27000], ['Leonardo', 27000], ]". I don’t know how to convert her.

  • How do you get the value of this String on your server?

  • @Enzotiezzi I make a query in a database through a file . ashx, concateto and return a string in the above format and return it pro ajax with a context.Response.Write(valores.ToString()); but you can also read this as context.Response.Write("[['Empresa_', 'Colaboradores'], ['Cleber', 27000], ['Jonathan', 27000], ['Leonardo', 27000], ]");

  • then, if you can, put this part that you said concatenates, because then we can try to solve in a way that already comes the correct information, or at least the most correct possible.

  • @Enzotiezzi posted the code, also tried to create an array with Ajax but it accuses "0x800a03f6 - Error in Javascript execution time: Invalid character". Code: var vet = JSON.parse(Values); var data = google.visualization.arrayToDataTable(vet);

  • All right, now let’s wrap this up, it has to be fixed by the server side itself, let’s go

  • let’s make a try, the variable valores will become a List<string> valores = new List<string>(); and you already put there the value you want in her, valores.Add("['Empresa_', 'Colaboradores']");, this is the first step

  • @Enzotiezzi left the code like this: comando.Connection.Open();List<string> valores = new List<string>();valores.Add("[['Empresa_', 'Colaboradores']");SqlDataReader dr = comando.ExecuteReader();while (dr.Read())&#xA; {if (dr["NOMEFANTASIA"] != DBNull.Value && dr["QTD"] != DBNull.Value){valores.Add(",['" + dr["NOMEFANTASIA"].ToString() + "'," + dr["QTD"].ToString() + "]");}} valores.Add(", ]");&#xA; comando.Connection.Close();

  • makes a variable String valor and within their ifs, replaces the variable valores for valor and at the end of his while adds valores.Add(valor); and valor = String.Empty;

  • @Enzotiezzi did this and executed with an Alert(Values); to see how he would return. Returned in Alert a System.Collections.Generic.List'1[System.String] but it still continues with the error Unhandled Exception at line 181, column 38 in https://www.google.com/uds/api/visualization/1.0/4e64ac79740513f5765562c361042389/format+pt_BR,default+pt_BR,ui+pt_BR,corechart+pt_BR.I.js 0x800a139e - Javascript runtime error: Not an array when trying to set the variable value date in Ajax

  • gives a look if on the server side, the list is with the desired values.

  • 1
Show 8 more comments

1 answer

1


I did a test using these links and managed to use Generic Handler using this library

https://github.com/zoranmax/GoogleDataTableLib

and the code available on the Chart google Docs (https://developers.google.com/chart/interactive/docs/php_example)

another answer: https://stackoverflow.com/questions/2363721/how-to-create-the-google-datatable-json-expected-source-using-c

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>
<script type="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; }
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.