What is the best way to access a Python API or local data within the Google Visualization DataTable JavaScript library?

I have been tirelessly working for the past two weeks to figure out how to load a local CSV file into google.visualization.DataTable() or use Ajax to call a Python Flask API that I created. My ultimate goal is to dynamically create a Gantt chart.

Here's a snippet of my code:

    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" ></script>
    <script type="text/javascript">
    
    // Load the Visualization API and the gantt package.
    google.charts.load('current', {'packages':['gantt']});
    google.charts.setOnLoadCallback(drawChart);
    
    function daysToMilliseconds(days) {
      return days * 24 * 60 * 60 * 1000;
    }
    



  function drawChart() {
      var jsonData = $.ajax({
          url: "http://127.0.0.1:5042/crudSEapi/D3test",
          dataType: "json",
          async: false
          }).responseText;
          var jsonData = JSON.parse(jsonData);
          var data = new google.visualization.DataTable(jsonData);
      
      console.log(jsonData["Column 0"])
      data.addColumn('string',jsonData["Column 0"]);
      data.addColumn(jsonData["Column 1"][1], jsonData["Column 1"][0]);
     
      
      data.addRows([
        [jsonData["Column 1"][2]]
       
      ]);

        var options = {
          height: 275,
          gantt: {
            criticalPathEnabled: false, 
            arrow: {
              angle: 100,
              width: 5,
              color: 'green',
              radius: 0
            }
          }
        };
        var container = document.getElementById('chart_div');
        var chart = new google.visualization.Gantt(container);
    
    google.visualization.events.addListener(chart, 'ready', function () {
      throw new Error('Test Google Error');
    });

      google.visualization.events.addListener(chart, 'error', function (err) {
        

      });
        chart.draw(data, options);
    }



  </script>
         
     
          <main id="main">
              <section id="data-section">
                  <h2>Data Input</h2>
                  <div id="data"></div>
              </section>
          </main>
          <h2>chart output</h2>
    
          <div id="chart_div"></div>
      
      <script>
          function apicall(url) {
              $.ajax({
                  type:"POST", url:url, 
                  success: (data) => { $("#data").html(data); }
              });
          }
          window.onload = function () {
              apicall("http://127.0.0.1:5042/crudSEapi/D3test");
          }
      </script>>

 

No matter how many tutorials I watch, I'm struggling to grasp how to make an Ajax call from my Python Flask API, retrieve the necessary data, and utilize it in google.visualization.DataTable() for dynamic Gantt chart creation. Your assistance is greatly appreciated!

My main hurdle lies in my lack of expertise in JavaScript. How do I fetch data from an API or a local CSV? How can I appropriately parse and structure this data for consumption by google.visualization.DataTable()? A straightforward example would be incredibly helpful...please lend me your guidance.

Snippet of my Python Flask Api Code:

import json
@crudSEapi.route("/D3test", methods=["GET", "POST"])
def d3():
    df = pd.read_csv("SkillBook/static/Sheet4.csv")
    chartdata = df.to_json()
    data = json.dumps(chartdata, indent=2)
    print(data)
    return Response(data)

CSV file excerpt:

id,title,start,end,dependencies,completed
m1,milestone 1,addDuration(startOfDay(new Date()),addDuration(startOfDay(new Date()),m2: start-to-start,0.6
m2,milestone 2,addDuration(startOfDay(new Date()),addDuration(startOfDay(new Date()),[m3: end-to-start,m4: end-to-end],0
m3,milestone 3,addDuration(startOfDay(new Date()),addDuration(startOfDay(new Date()),,0.75
m4,milestone 4,addDuration(startOfDay(new Date()),addDuration(startOfDay(new Date()),,0.2

The desired output should resemble this: https://i.stack.imgur.com/JW7rU.png

Answer №1

I successfully resolved the issue with the assistance of @WhiteHat.

<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9cf6ede9f9eee5b1ffefeadcadb2acb2aead">[email protected]</a>/src/jquery.csv.js"></script>
<div id="chart_div"></div>
<li><input></li>
<li><input></li>
<li><input></li>
<button>update data in chart</button>
<button>print SVG</button>
<script>
   function toMilliseconds(minutes) {
     return minutes * 60 * 1000;
   }
   
   google.charts.load('current', {
     callback: function () {
       $.get("/static/Sheet4.csv", function(csvString) {
         var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
         console.log(arrayData[6][1])
         var data = new google.visualization.DataTable();
     
         data.addColumn(arrayData[2][1], arrayData[1][1]);
         data.addColumn(arrayData[2][2], arrayData[1][2]);
         data.addColumn(arrayData[2][4], arrayData[1][4]);
         data.addColumn(arrayData[2][5], arrayData[1][5]);
         data.addColumn(arrayData[2][6], arrayData[1][6]);
         data.addColumn(arrayData[2][7], arrayData[1][7]);
         data.addColumn(arrayData[2][8], arrayData[1][8]);
         data.addRows([
         [
         arrayData[3][1],
         arrayData[3][2],
           null,
           null,
           toMilliseconds(5),
           100,
           null,
         ],
         [
         arrayData[4][1],
         arrayData[4][2],
           null,
           null,
           toMilliseconds(70),
           100,
           null,
         ],
         [
         arrayData[5][1],
         arrayData[5][2],
           null,
           null,
           toMilliseconds(10),
           100,
           arrayData[3][1],
         ],
         [
         arrayData[6][1],
         arrayData[6][2],
           null,
           null,
           toMilliseconds(45),
           75,
           arrayData[5][1],
         ],
         [
         arrayData[7][1],
         arrayData[7][2],
           null,
           null,
           toMilliseconds(10),
           0,
           arrayData[6][1],
           ],
         [
         arrayData[8][1],
         arrayData[8][2],         
          null,
           null,
           toMilliseconds(2),
           0,
           arrayData[5][1],
         ],
       ]);
         
   
         var options = {
           height: 275,
           gantt: {
             criticalPathEnabled: false, 
             arrow: {
               angle: 100,
               width: 5,
               color: 'green',
               radius: 0
             }
           }
         };
         var container = document.getElementById('chart_div');
         var chart = new google.visualization.Gantt(container);
     
   
         chart.draw(data, options);
       });
     },
     packages: ['gantt']
   });
   
</script>

Also, here is my CSV data:

step0,step1,step2,step3,step4,step5,Step6,step7,step8
Purpose,Task ID,Task Name,Resource ID,Start,End,Duration,Percent Complete,Dependencies
Data Type,string,string,string,date,date,number,number,string
Project1data1,Test1,test1x,test1y,test1z,0,1,2,test1a
Project1data2,Test2,test2x,test2y,test2z,0,1,2,test2a
Project1data3,Test3,test3x,test3y,test3z,0,1,2,test3a
Project1data4,Test4,test4x,test4y,test4z,0,1,2,test4a
Project1data5,Test5,test5x,test5y,test5z,0,1,2,test4a
Project1data6,Test6,test6x,test6y,test6z,0,1,2,test4a
Project1data7,Test7,test7x,test7y,test7z,0,1,2,test4a

Future steps include: Implementing dynamic input changes by creating a form on the website Ensuring the ability to upload and parse CSV files of any size

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

Switching between sockets on a rotational basis

Imagine there is a division in the HTML file, and an interesting game is being played where each player has the opportunity to change the color. However, there’s a twist – they can only switch colors after the other player has taken their turn. The pla ...

"Creating a cohesive design: Using CSS to ensure the navigation background complements

I am working on a project with a horizontal navbar that I want to stay fixed while scrolling. The main window has different colored divs as you scroll down, and I would like the navbar to match the image of the main div while scrolling, creating a looping ...

Edit the contents within HTML strings without altering the HTML structure

If I have a string of HTML, it might look something like this... <h2>Header</h2><p>all the <span class="bright">content</span> here</p> I am interested in manipulating the string by reversing all the words. For example ...

Transform CVS file into JSON format while allowing duplicate keys

Working on a project, I receive data in an Excel sheet which I convert to CSV using Excel. These files contain measurements with different categories but the same ID. For example: readingId; category; result; 1 ; cat 1 ; A 1 ; cat 2 ; B ...

Switching a cookie from JavaScript to AngularJS: A step-by-step guide

Getting a cookie in AngularJS can be done in a more standardized way. Instead of the traditional JavaScript approach, you can implement it using AngularJS code as shown below: angular.module('myApp', []) .factory('CookieService', func ...

"Exploring the Dynamic Display of Ajax with HTML5 Canvas

This is my first time exploring the world of ajax, and I'm finding it quite challenging to grasp the concept and functionality. What I aim to achieve: I envision a scenario where I can freely draw on a canvas and simply hit save. Upon saving, the da ...

Javascript regular expressions are not functioning as expected

When testing the string "page-42440233_45778105" against the pattern "(page-\d+_\d+)", an online tester at was able to successfully find a match. However, when executing the code in browser js, the result is null. Why might this be? var re = ne ...

Update the Material-UI theme to a personalized design

I am currently using Material-UI in my React project. However, I'm facing some difficulties in applying a theme globally. Up until now, I have only managed to apply the theme to individual components like this: import { MuiThemeProvider, createMuiTh ...

Utilizing Django Ajax to specify a URL with two dynamic URL paths (e.g. <str: 'first_variable'>/<str: 'second_variable'>/fetch/)

I've created a Django ajax template to retrieve all the Players from a players model: <body> <h1>List of Players:</h1> <ul id="display-data"> </ul> </body> <script> $(document).ready(fun ...

When the onClick method is triggered, it retrieves a single object from json_encode

Currently, I am using the json_encode method on data extracted from a table. After applying a var_dump to this variable, it reveals three objects: {"id": "5"} {"id": "6"} {"id": "7"} Here's my process: I have an image with an onclick function: < ...

Having trouble adjusting the refresh timer based on user focus with setTimeout

For the past few days, I've been utilizing an ajax call to dynamically refresh specific elements of my webapp every 5 seconds. The implementation with setInterval(refreshElements, 5000) worked perfectly fine. However, now I am considering whether the ...

"Encountering a challenge when trying to fetch the value of an undefined or null

When it comes to validating the delivery date entered, I have implemented the following code to ensure it is not earlier than the current date... I have utilized custom validation using jQuery... Here is my model: [UIHint("Date")] [DeliveryDateC ...

Utilizing the power of JavaScript/JQuery to showcase a compilation of all input values within an HTML form

I'm struggling to showcase all the input values from my HTML form on the final page before hitting the "submit" button. Unfortunately, I am facing a challenge as the values are not appearing on the page as expected. Despite several attempts, the valu ...

Utilizing Axios to filter response.data in an API request

Looking to retrieve the latest 8 products based on their date? Take a look at the code snippet below: const newestProducts= []; axios.get("http://localhost:3003/products").then(response => { let products = response.data.sort(fu ...

How can I loop through SVG elements and attach an event listener to each one in JavaScript?

I am struggling with loading a simple SVG file and iterating through the shape nodes to add an onclick event. Unfortunately, after the SVG file is loaded, it cannot find the shape nodes. What could be the issue here? Here is the SVG code snippet: < ...

Next.JS: The Key to Long-Term Data Storage

How can we retrieve and maintain data during app initialization or user login so that it persists throughout the application? Currently, every time a page is refreshed, the context is cleared and attempting to use getServerSideProps results in undefined ...

The v-tab-item content is not loading properly when the component is initialized in the mounted hook

I'm working on a project that utilizes Vuetify tabs to showcase two different components under separate tabs. The problem I'm encountering is that, within the mounted() function, when attempting to access the refs of the components, only the ref ...

Is it possible to access the passed arguments in the test description using jest-each?

Utilizing TypeScript and Jest, consider this sample test which can be found at https://jestjs.io/docs/api#testeachtablename-fn-timeout it.each([ { numbers: [1, 2, 3] }, { numbers: [4, 5, 6] } ])('Test case %#: Amount is $numbers.length =&g ...

What is a more efficient way to avoid duplicating code in javascript?

Is there a way to avoid repeating the same code for different feeds? I have 8 feeds that I would like to use and currently, I am just incrementing variable names and feed URLs. <script type="text/javascript> function showFeed(data, content ...

Traverse through the loop with React Material UI in JavaScript

Hi everyone, I'm having trouble with this code. I want to iterate through an object called paleogenome.data and create a CardHeader for each item: { Object.keys(paleogenome.data).forEach(function (key){ console.log(paleogenome.data[key] ...