Leveraging Flask to pass data to Google Charts with JavaScript

Trying to integrate Google Charts on my website using Flask as the backend. Need help with sending data from Flask to JavaScript. Here's a snippet of where I plan to retrieve data later:

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

How can I utilize the '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]
    ]);

Currently using predefined data, but plan to dynamically pull data from a SQLite database in the future for actual use.

Appreciate any assistance :D

Answer №1

To add any incoming data to the render_template (in this case, data), simply wrap them in double curly braces {{}}. For instance, consider using chart.js as shown below:

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

In this example, time_series and data_points are passed as lists. To simplify the code, you can also utilize the for statement.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize new metadata options to incorporate an external style and script file

I'm looking to incorporate external CSS and scripts into my NextJS app (NextJS version 13.4.13). Here's what I need: Style https://company.com/statics/1/package/dist/1/styles/dls.min.css Script https://company.com/statics/1/package/dist/1/ ...

What is the mechanism behind jQuery triggering the execution of JavaScript code contained in script tags that are retrieved in an AJAX response?

What is the unique ability of jQuery that allows JavaScript code inside script tags in an AJAX response to be executed? In the absence of jQuery AJAX, using eval() has been a common method to achieve this functionality as discussed in posts such as: Cal ...

React Native Header Icon Not Showing on the Left Side

I'm brand new to react and currently working on a project where navigation is done through a hamburger menu. I haven't encountered any errors in my code, but for some reason, the hamburger menu icon isn't displaying as expected. Interestingl ...

When troubleshooting the "Uncaught reference error: require is not defined," the browserify command encountered the error message "Error: Cannot find module."

I am encountering a similar issue to @RachelD in the thread discussing the Uncaught reference error. When I execute the 'browserify' command following the instructions provided here, and using my directory as a reference, like so... myname@compn ...

Creating a callback function within stored procedures using JavaScript Language Integrated Query in documentDB: A step-by-step guide

According to the documentation, the code snippets below are considered equivalent. However, I have observed that in the first case, I am able to perform operations on multiple documents within the callback function, whereas the map function in the latter s ...

Inserting a custom text box underneath the Anything Slider

I am currently incorporating the Anything Slider into a website project. The main purpose of the slider is to showcase videos, but I would like to include a description text box beneath it that dynamically changes based on the selected tab. This snippet de ...

The color of the last clicked DIV is supposed to stay permanent, but for some unknown reason

I'm attempting to replicate this design in my project: http://jsfiddle.net/AYRh6/26/ However, I am facing issues with it and cannot pinpoint the exact problem in the code. I am using code for a toggle effect. Any assistance would be greatly appreciat ...

Is NodeJS Asynchronous: Has the callback been called twice?

I'm currently working with the Async module in Node.JS to manage my asynchronous calls. However, I've encountered an issue stating "Callback already called." Could someone assist me with resolving this problem? async.each(data['results&apos ...

"How can you enhance the performance of JavaScript and CSS in a Chrome Extension without using exclude_matches/globs or excluding domains

I have been in the process of creating a Chrome Extension, and unfortunately, when I tried to make it work on specific URLs, I encountered an issue. While Chrome has options like exclude_matches and exclude_globs for this purpose, there seems to be a bug i ...

Having trouble with my ReactJS application where click interactions are functioning properly on the header but not on my content

Objective: Implement an iframe displaying a YouTube video with play/pause functionality for users. Issue: Unable to interact with main content, but works correctly when placed in Navigation or Footer components. Attempted Solutions: Explored various de ...

The functionality of the webservice is not functioning properly

I'm currently working with Express and NodeJS to create a simple hello world webservice. I am attempting to call this webservice in ReactJS using Axios, but I am encountering issues with the response from the webservice. Below is my code for the webse ...

Challenges with dynamically adding rows using jQuery

I am trying to create a dynamic form that allows users to select a project and then populates tasks based on the selected project from a database query. The user can then enter hours for each task, which are updated based on the project id and task id comb ...

Strikeout list on click of a mouse

Is there a way to apply strikethrough formatting to text with just a mouse click? The CSS for lists is beyond the form field margin. I've tried multiple methods without success. No matter how many times I change the code, I can't seem to get it r ...

Tips for successfully sending an interface to a generic function

Is there a way to pass an interface as a type to a generic function? I anticipate that the generic function will be expanded in the future. Perhaps the current code is not suitable for my problem? This piece of code is being duplicated across multiple fil ...

trigger an event once an element has completed cycling using cycle.js

Incorporating the cycle.js library for simple transitions between images: $(document).ready(function() { var first; var $slider = $(".trauringe"); $slider.cycle({ timeout: 8000, next: '#next', prev: '#prev' ...

Looking for a way to create a regular expression that can parse an email response containing the newline character?

Do you need help parsing only the most recent reply from the email thread below? For example, Hello Nikhil Bopora,↵↵Just to give a brief, I am in process of building an alternate e-lending↵platform. I tried using the general regex /[\s]*([&bsol ...

Preventing Jquery Append from Adding Previous Elements

I am struggling to figure out how to display the star rating for each hotel individually. I have 5 hotels, each with a different star rating. Here is my Javascript code: function GetStarHotel() { var parent = $(' p.star '), imagePat ...

D3 Treemap for handling extensive sets of data

I am uncertain if there exists a method to incorporate the desired feature. I am seeking a solution similar to zoomable treemaps, but to initially load a limited number of child levels and then dynamically add more child nodes without requiring a node clic ...

PHP fails to retrieve data from a JavaScript Ajax function using the FormData object (specifically, when

I'm facing an issue where my file is not being detected when I send a FormData object using AJAX and PHP code. Both the `$_FILES` array and the `$_POST` array appear to be empty. However, the browser does send the file with the AJAX request. <inpu ...

Incorporating interactive maps into an AngularJS web application

I've been attempting to integrate Google Maps into my AngularJS application, using the script tag below: <script src="https://maps.googleapis.com/maps/api/js?key=[MySecretKeyHere]&callback=initMap" async defer></script> I found this ...