Charts.js Problem to bring Data to the chart!

Asked

Viewed 62 times

0

I have a Google Charts chart that works perfectly bringing the database data through ajax, but I tried to do the same with Charts.js and I can’t. I would like to know how I put real data on the Charts.js chart by taking advantage of my already created Function get to the other chart.

// ESTA E A FUNCTION DO GRAFICO GOOGLE CHARTS QUE FUNCIONA, COM AS "CONST" TRAZENDO OS DADOS

async function drawChart15() {
            const qtndVitimas = await GetQuantidadeVitimas()
            const qtndAutores = await GetQuantidadeAutor()
            const container = document.querySelector('#graficoGoogle16')
            const data = new google.visualization.arrayToDataTable([
                ['Legendas', 'Abril', 'Agosto', "Setembro", "Novembro", "Dezembro"],
                [qtndVitimas, qtndVitimas, qtndAutores, qtndVitimas, qtndAutores, qtndVitimas], 
            ])
            const options = {                
                height: 250,
                width: 500
            }
            const chart = new google.visualization.ColumnChart(container)
            chart.draw(data, options)
        }

Now I will show the two Function that I created to pull the data through ajax.

// AMBAS FUNCTION ESTÃO TRAZENDO OS DADOS CORRETAMENTE

async function GetQuantidadeVitimas() {
            let qtnd_vitimas = 0
            const url = `/Vitima/AjaxQuantidadeVitimas`

            try { 
                const resposta = await fetch(url);
                const resultado = await resposta.json();

                qtnd_vitimas = resultado
            } catch (e) {
                console.error(e);
            }
            return qtnd_vitimas;
        }

        async function GetQuantidadeAutor() {           
            let qntd_Autores = 0
            const url = `/Autor/AjaxQuantidadeAutores`

            try { 
                const resposta = await fetch(url);
                const resultado = await resposta.json();

                qntd_Autores = resultado
            } catch (e) {
                console.error(e);
            }
            return qntd_Autores;
        }

These two functions return the number of victims and authors registered in the database. I will show the step by step of Getnumerovitimas().

//aqui pegando os dados do banco

public int GetNumeroVitimas()
        {
            using (IDbConnection cn = ConnectionAnaliseCriminal)
            {
                try
                {
                    cn.Open();
                    string query = "SELECT COUNT(TP_VITIMA.COD_VITIMA)"
                        + " FROM [dbo].[TP_VITIMA] "
                        + " WHERE TP_VITIMA.[DT_EXCLUSAO_LOGICA] IS NULL ";

                    return cn.Query<int>(query).SingleOrDefault();
                }
                finally
                {
                    cn.Close();
                }
            }
        }

//Passa pela ControllerBase


protected int NumeroVitimas(int codFormulario) => new VitimaDados().GetNumeroVitimas(GetCodCrimeByCodFormulario(codFormulario));

// dps a "VitimaController onde e add a viewbag e o ajax

ViewBag.NumeroVitimas = NumeroVitimas(codFormulario);

[HttpGet]
    public JsonResult AjaxQuantidadeVitimas()
    {
        return Json(new VitimaDados().GetNumeroVitimas());
    }

Now I wanted to do the same thing with the Charts.js chart to show the actual data coming from the database but I’m not getting it. Does anyone know how to solve?

// SCRIPT PURO DO CHARTS.JS PORÉM EU QUERO INSERIR NA "DATA" OS MEUS DADOS VINDO DO BANCO PELO AJAX, ASSIM COMO FIZ NO OUTRO GRÁFICO, PORÉM NÃO ESTOU CONSEGUINDO

var ctx = document.getElementById('myChart');
var chart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: 'titulo grafico',
            data: [1, 2, 3, 4, 5, 6],
            borderColor: 'rgba(77,166,253,0.85)',
            backgroundColor: 'red',
        },        
        ]
    },    
});
<html>
<head>
<title></title>
</head>
<body>

<canvas id="myChart"></canvas>

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</body>
</html>

  • No matter the google Harts for this question... you have to submit what return /Vitima/AjaxQuantidadeVitimas and /Autor/AjaxQuantidadeAutores. And after all your backend is php or c#?

  • All in c# and they return the number of registered authors and victims.

  • So why the php tag on the question? Present their feedback and the action with the model in the backend

  • Okay, I added the feedback of one, more and the same procedure of the other.

  • It wouldn’t just be in the method where you create Chart to previously call the collection functions?

  • @M.Bertolazo can be, more as I would do it, can give an example in the script?

  • Wouldn’t that solve? date: [Getquantityavoidances(), 2, 3, 4, 5, 6]

  • @M.Bertolazo and to call my duties in Chart as would?

  • your method GetNumeroVitimas() returns only an integer, does not have an argument to filter by month... I think the first step would be to create a consultation that brings the total number of victims grouped per month.... I already say that this is another question

  • @Leandroangelo then more before doing this, I wanted to use the same more method on the chart of Charts.js as my previous question, in case as I would do?

  • It won’t, because it doesn’t meet that need

  • @Leandroangelo Sorry I don’t understand. I’m beginner in the area of Backend, if you can explain me better I would appreciate it very much. What does not meet the need and what I must do?

  • It’s not the back end issue... even on the google chart, what you’re displaying doesn’t make any sense. You’re just repeating numbers in different positions... What do you want to represent with this graph?

  • @Leandroangelo I want to represent the total number of victims and authors, the repeated numbers are just examples that I will change later.

Show 9 more comments

1 answer

0


What you’re implementing, it doesn’t make any sense, but since you insist so much...

Even on the google chart, what you’re displaying doesn’t make any sense. It’s just repeating numbers at different positions... What you want to represent with this chart?

   async function drawChart15() {
        const qtndVitimas = await GetQuantidadeVitimas()
        const qtndAutores = await GetQuantidadeAutor()
        const container = document.querySelector('#graficoGoogle16')
        const data = new google.visualization.arrayToDataTable([
            ['Legendas', 'Abril', 'Agosto', "Setembro", "Novembro", "Dezembro"],
            [qtndVitimas, qtndVitimas, qtndAutores, qtndVitimas, qtndAutores, qtndVitimas], 
        ])
        const options = {                
            height: 250,
            width: 500
        }
        const chart = new google.visualization.ColumnChart(container)
        chart.draw(data, options)
    }

In the backend, method GetNumeroVitimas() returns only an integer with the total number of victims, as it does not receive any argument it will always bring the same result given to the query being made in the database. And I believe you have the same problem in the author query.

string query = "SELECT COUNT(TP_VITIMA.COD_VITIMA)"
    + " FROM [dbo].[TP_VITIMA] "
    + " WHERE TP_VITIMA.[DT_EXCLUSAO_LOGICA] IS NULL ";

Now see in the example below how none of this makes sense. Ignoring the backend, because the result would be the same, only with two different numbers. That’s what you’re doing

function GetQuantidadeVitimas() {
  let qtnd_vitimas = 10;
  return qtnd_vitimas;
}

function GetQuantidadeAutor() {
  let qntd_Autores = 7;
  return qntd_Autores;
}
var qtdVitimas = GetQuantidadeVitimas();
var qtdAutores = GetQuantidadeAutor();

let ctx = document.getElementById('myChart');
let chart = new Chart(ctx, {
   options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    },
  type: 'bar',
  data: {
    labels: ["Abril", "Agosto", "Setembro", "Novembro", "Dezembro"],
    datasets: [{
      label: 'Qualquer coisa',
      data: [qtdVitimas, qtdAutores, qtdVitimas, qtdAutores, qtdVitimas],
      borderColor: 'rgba(77,166,253,0.85)',
      backgroundColor: 'red',
    }, ]
  },
});
<html>

<head>
  <title></title>
</head>

<body>

  <canvas id="myChart"></canvas>

  <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</body>

</html>

Still abstracting the question of values and the backend, you need a dataset for each type of data you want to represent.

function GetQuantidadesVitimas() {
  let arrVitimas = [2,4,3,5,1];
  return arrVitimas;
}

function GetQuantidadesAutor() {
  let arrAutores = [1,3,2,4,1]
  return arrAutores;
}
var qtdVitimas = GetQuantidadesVitimas();
var qtdAutores = GetQuantidadesAutor();

let ctx = document.getElementById('myChart');
let chart = new Chart(ctx, {
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  },
  type: 'bar',
  data: {
    labels: ["Abril", "Agosto", "Setembro", "Novembro", "Dezembro"],
    datasets: [{
        label: 'Vítimas',
        data: qtdVitimas,
        borderColor: 'rgba(77,166,253,0.85)',
        backgroundColor: 'red',
      },
      {
        label: 'Autores',
        data: qtdAutores,
        borderColor: 'rgba(77,166,253,0.85)',
        backgroundColor: 'blue',
      }
    ]
  },
});
<html>

<head>
  <title></title>
</head>

<body>

  <canvas id="myChart"></canvas>

  <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</body>

</html>

Now you need to understand this structure change the in your backend the queries the methods to get these results.

  • I think I understand better now, thank you.

  • But there’s one thing I don’t understand, in the part "Let arrVitimas" and "Let arrAutores" you put fixed numbers, but I want the values to come from the bank, as I do?

  • That’s what I’m saying from the beginning... this issue is closed... now you need to look in your backend, how to consult the bank and return the values in this format... After that you already have the original method that makes the request via ajax to get this data.

  • @Mizrainphelipesá now, if you are not willing to understand that, you are attacking the problem by the wrong end and do not want to break your doubts in pieces. The best I can do is remove the answer and vote to close your question...

  • Now I realize that I lack more backend study to be able to continue in this process. thanks for the effort and willingness!

Browser other questions tagged

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