Using flask returned data in google charts in js

Viewed 43

I'm trying to use google charts on my website and i'm using flask as backend , but i don't know how to send data from flask to js, got this where i'm gonna get data from later on

@app.route("/")
def home():
    data = {'Language': 'DATABASE','PHP': 5000,'ASP': 600,'ASPX': 1231,'PERL': 500,'JSP': 1000}
    return render_template('index.html', data=data)

but how do i use that 'data=data' here :

function drawChart(stats) {
    var stats = '{{stats}}'
    var data = google.visualization.arrayToDataTable([
        ['Language', 'IN DATABASE'],
        ['PHP', 5000],
        ['ASP', 600],
        ['ASPX', 1231],
        ['PERL', 500],
        ['JSP', 1000]
    ]);

Here i'm just using a predifined var but later on i'm gonna pull data from a sqlite db and use it istead of that data var which is just for testing purposes.

Thanks in advance :D

1 Answers

You can include any passed data into the render_template(in your case, data) by enclosing them within {{}}. Giving an example of chart.js:

<canvas id="myChart" width="100%" height="40%"></canvas>
                                            <script type="text/javascript">
                                            var ctx = document.getElementById("myChart");
                                            var xaxis = ['{{graph_year[0]}}', '{{graph_year[1]}}', '{{graph_year[2]}}', '{{graph_year[3]}}', '{{graph_year[4]}}', '{{graph_year[5]}}']
                                            var yaxis = ['{{graph_returns[0]}}', '{{graph_returns[1]}}', '{{graph_returns[2]}}', '{{graph_returns[3]}}', '{{graph_returns[4]}}', '{{graph_returns[5]}}']
                                            ctx.style.backgroundColor = 'rgba(255,255,255,1)';
                                            var myChart = new Chart(ctx, {
                                                type: 'bar',

Here, graphyear and graphreturns were passed as list type. You can also use the for statement to shorten the code.

Related