0

Assume that I want to make a bar chart in HTML. I use node.js as a backend and get data from the database through node.js. I usually will render the data to view into ejs files. Is it possible for me to use database data from node.js then pass it to javascript (client-side) where I am creating the chart.js?

0

1 Answer 1

1

Try this: replace result with your data!

const fs = require('fs');
var express = require('express');
var app = express();
var path = require('path');
var Chart = require('chart.js');
var result =[3,6,9];

app.get('/', function(req, res){
    let _resLine = '<h1>Ereignisse: ' + result+'</h1>';
    console.log('show chart:');
    console.log(_resLine);

    _html = "<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js'></script>"+
    "<canvas id='bar-chart' width='800' height='450'></canvas>"+
    "<script>"+
    "var logChart = new Chart(document.getElementById('bar-chart'), {"+
    "type: 'horizontalBar',"+
    "data: {"+
      "labels: ['Ereignis1', 'Ereignis2', 'Ereignis3'],"+
      "datasets: ["+
        "{"+
          "label: 'Aufrufe',"+
          "backgroundColor: ['#3e95cd', '#8e5ea2','#3cba9f'],"+
          "data: ["+result[0]+","+result[1]+","+result[2]+"]"+
        "}"+
      "]"+
      "},"+
    "options: {"+
      "legend: { display: false },"+
      "title: {"+
        "display: true,"+
        "text: 'Ereignisse '"+
      "}"+
    "}"+
    "});"+
    "</script>";

    res.send(_html);
});

app.listen(3005);

cmd: node showChart.js URLs: http://localhost:3005

See also example in my git archive

Sign up to request clarification or add additional context in comments.

1 Comment

Hi! @Micha Your answer was very helpful, but currently I have a problem, I need to add labels on top of my graph, I have searched how to do it and among them use plugins to do it but when using this way to do it it does not seem to work, how could I do it? Could you help me?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.