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

The form data submitted by jQuery is inaccurate

I am currently facing an issue with my jQuery implementation. I have a jQuery UI dialog containing a form, which is submitted using the ajax function of jQuery. The problem arises when I try to edit certain fields within a table using the same dialog. Aft ...

Using JavaScript to generate dynamic folders in Alfresco is not functioning as expected

Working with Alfresco 4.0.d community edition (also tested on Alfresco 4.0.c) on an Oracle Linux 64-bit virtual machine using Firefox. I've been developing a script to dynamically create sub-folders as new items are added to a space/folder via a rule ...

Exploring the compatibility of Husky with Typicode using Yarn

Currently, I have implemented the use of husky to configure git hooks for prettier. However, I am facing a persistent issue whenever I attempt to commit or push: > husky - Can't find npm in PATH. Skipping precommit script in package.json My curre ...

Ways to extract data from an array nested within a JSON object

I am seeking guidance on how to access the value of "result 2" from my JSON object using jQuery or pure JavaScript. var jsonarray = [{ title: "Category1", items: [{ result: "Item1", //Nested array items2: [{ //How to get the value o ...

Experiencing Difficulty accessing Methods with Jmeter-Webdriver

var pkg = JavaImporter(org.openqa.selenium) var support_ui = JavaImporter(org.openqa.selenium.support.ui.WebDriverWait) var wait = new support_ui.WebDriverWait(WDS.browser, 5000) **var support_page=JavaImporter(org.openqa.selenium.WebDriver.Timeouts)** **v ...

Using Material UI with Reactjs for Background Image Mapping

I need some advice from everyone. I have an array of images and I've mapped the content, but for some reason I am unable to set a background image in the styles of a component. The other objects in the array are working as expected. {DlCards.map((mdlc ...

How can we leverage JavaScript to create logistic regression models for datasets and derive the beta-coefficients?

Exploring Logistic Regression in JavaScript In my current project, I am looking to fit a multi-variate logistic regression model to a dataset using JavaScript. My main goal is to extract the beta-coefficients for this model. Can anyone provide guidance on ...

A guide on showcasing nested arrays data in an Angular application

info = [ { list: [ { title: 'apple'} ] }, { list: [ { title: 'banana'} ] } ] My goal here is to extract the list items. Here is how they are structured. desired r ...

Transmit data from the Windows Communication Foundation to JavaScript

Looking to invoke the WCF service through JavaScript, utilizing AJAX? Check out this resource: Calling WCF Services using jQuery Here's my query: Is there a method to retain some JavaScript-related data after making a request, and then transmit inf ...

`In HTML, trigger blocks based on the number chosen by the user`

I am working on creating a web page where users can select the number of friends they have, and based on that input, a corresponding number of invisible boxes will be triggered. For example, if a user selects 3 friends, 3 boxes will appear for them to ente ...

"Perform an Ajax check on the webpage prior to proceeding with

I'm using an ajax.php file as the target for all my AJAX calls, including an additional parameter specifying the script to execute. However, I need to restrict certain scripts to be executed only from specific pages. For example, sendComment.php shoul ...

A custom class that uses toggleClass() does not trigger an alert upon a click event

I am encountering an issue with the toggleClass() function in jQuery that I haven't seen addressed before. Despite successfully toggling the class of one button when clicked, I am unable to trigger a click event on the newly toggled class. Here is th ...

Angular - The argument provided is not compatible with the parameter

I encountered the following TypeScript errors in app.component.ts: Issue: Argument of type '(events: Event[]) => void' is not assignable to parameter of type '(value: Event[]) => void'. Description: Types of parameters 'events& ...

Click on the checkboxes to the left labeled "Mark"

https://i.stack.imgur.com/2u1dI.png In designing a permission management form for user access, the concept I have in mind is as follows: When "Manage" is selected, the options for view/edit/lend should also be automatically selected and disabled. If any ...

Unable to create property within array in model

I am facing an issue while trying to access the name property of an array called Model[] generated from my Model.ts file. When attempting to use it in my app.component, I receive an error stating that the property 'name' does not exist on type Mo ...

Converting a string into a regular expression using JavaScript

I am attempting to change the color of a text element when specific variations of the word "hello" are entered into an input field. While this works with a regular string comparison, it fails when using a regular expression. <input id="input" type="inp ...

Next Value in Array Following Selected One

Apologies for the repetition, but despite my attempts, I haven't been able to find a solution that works for me. When a user clicks on an element, I need to retrieve the following information: The ID of the selected element An array containing all v ...

Custom control unable to display MP3 file

Hey, I came across this awesome button that I am really interested in using: https://css-tricks.com/making-pure-css-playpause-button/ I'm currently facing two issues with it. First, I can't seem to play the sound. I've placed the mp3 file ...

Does the current protected route that I am on restrict the user from navigating back to the Home component?

I'm having trouble figuring out how to redirect the user to the Home component when they logout. The API is functioning correctly based on my tests. However, I am unsure of how to implement the logout method in the current context to successfully log ...

Having trouble getting npm install to add any libraries? Wondering how to fix this issue?

Currently, I am using Node version 14.15.5, npm version 6.14.11, and working on VS Code. I attempted to install two packages with the following commands: npm install express npm install lodash Unfortunately, neither installation was successful. This ...