Error in Google charts JavaScript library

I am currently attempting to generate a Google pie chart using data extracted from an Excel sheet. The string that is returned is outlined below, which I am passing into

google.visualization.arrayToDataTable();
. Here is the code snippet that I have implemented:

    <script type="text/javascript">
  google.charts.load("current", {packages:["corechart"]});
  google.charts.setOnLoadCallback(drawChart);
   var str = '<%= JSNstring %>';     //the string returned from C#.


  var res= str.replace(/""/g,"'");
  res=res.replace(/"/g,"'");
  // 
  var ss=[res];
  document.write(ss);    //the output of this is: 

[['Solution','TOTAL'],['Check',23],['FULL',18],['POP',109]]

  function drawChart() {
    var data = google.visualization.arrayToDataTable(ss);

    var options = {
      title: 'My Daily Activities',
      pieHole: 0.4,
    };

    var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
    chart.draw(data, options);
  }
</script>

The issue I am encountering is as follows:

JavaScript runtime error: First row is not an array.

Please advise on what mistakes I may be making and how I can address them effectively. Thank you in advance.

Answer №1

  `document.write(ss);`

Is this code specific to the example? If not, remove it and check the value of ss within your function like this-

function drawChart() {
console.write(ss);   
 var data = google.visualization.arrayToDataTable(ss);

    var options = {
      title: 'My Daily Activities',
      pieHole: 0.4,
    };

    var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
    chart.draw(data, options);
  }

Update

Try rewriting your drawChart() function as follows-

function drawChart() {
    var str = '<%= JSNstring %>';     //returned string from C#.


  var res= str.replace(/""/g,"'");
  res=res.replace(/"/g,"'");
  // 
  var ss=[res];
  var data = google.visualization.arrayToDataTable(ss);

    var options = {
      title: 'My Daily Activities',
      pieHole: 0.4,
    };

    var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
    chart.draw(data, options);
  }

Update 2

I have created a jsfiddle for you here, with your array hardcoded. As you can see, it works fine here. It seems that there might be an issue either on the server side or with the value of ss.

Answer №2

To properly handle the string and convert it into an array, you can follow these steps:

google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
 var dataString = '<%= jsonData %>';  //data returned from server-side code.


var parsedData= dataString.replace(/""/g,"'");
parsedData=parsedData.replace(/"/g,"'");
var dataArray='[' + parsedData + ']';

function drawChart() {
  var dataTable = google.visualization.arrayToDataTable(eval(dataArray));

  var options = {
    title: 'My Daily Activities',
    pieHole: 0.4,
  };

  var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
  chart.draw(dataTable, options);
}

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

Unable to retrieve the value of a JSON object

I have a JSON Object called contacts that has the following structure: {"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="337e524158737b5c5c58525b604752475a5c"><email address hidden></a>","phone":"+197969 ...

Server Tag Parsing Error in Asp.Net

Currently, I'm faced with a challenge while debugging a website - I seem to be stuck on this particular section of code. So far, my efforts to establish a connection between the site and an existing database have been futile as I keep encountering the ...

Ways to manage an element that has been loaded using the load query function

After implementing the query load function to update posts on the homepage, I was able to display the most up-to-date posts. However, a new issue arose: Whenever I updated all posts without refreshing the entire page, I needed a way to control the element ...

Tips for Omitting Hours, Minutes, and Seconds from AngularJS Date Display

Currently, I am retrieving data from a JSON file using the $http.get request. The format in which the date is received in my JSON file is as follows: "date": "2016-10-24 15:14:53" I would like to convert this date format to display as: October 10 2016 (e ...

Loop through a collection of items based on the values in a separate array using jQuery

I have a list of objects below The newlist and SelectID array are both dynamic. I am populating through a function, now I need to iterate and create the new list. var newList = [ { id : 1,name="tea",plant:"darjeeling"}, { id : 2,name="cof ...

Using ESP8266 to send JSON Parameters through HTTP POST Request

I am currently tackling a project where the ESP8266 initializes in softAP mode upon start up. The main page showcases a list of accessible WiFi networks. Users have the option to choose one and input the password for that network. This action triggers an ...

Retrieving JSON data containing peculiar characters and numerical values in iPhone SDK

I have been working on creating an iOS app that retrieves data from a SQL server using a PHP file in JSON format. The app functions perfectly when tested on Safari browser, and I have utilized the SBJSON framework to handle the JSON within my application. ...

Converting my HTML navigation menu to PHP

In the past, this is what I had: <li><a class="selected0" href="/dbp/dbma.html">Dashboard 0</a></li> <!-- First dashboard selection --> <li><a class="select1" href="#" onclick="r ...

Why is jQuery button function only functioning for the first button?

I'm encountering an issue with my table of records. Each row in the table has a submit button that triggers an AJAX request to the server when clicked. Strangely, the first button works perfectly and sends the request as expected. However, subsequent ...

Limit the vertical movement in Vue drag and drop operations

Currently, I am working on a project that involves implementing drag-and-drop functionality using vue-draggable. You can find more information about it here: https://github.com/SortableJS/Vue.Draggable. I am facing an issue where the height of the element ...

Retrieving the result of a LINQ query within a repository

How can I create a method inside an interface like this? List<T> OngoingEvent(); I have implemented the method inside the repository as follows: public List<T> OngoingEvent() { var output2 = DbContext.ParticipantsTable.Join(DbContext.Even ...

Using ReactJS to load JSON data into a state array

I am currently attempting to dynamically create a JSON object and append it into an array stored within the state. I have discovered that using concat is the only method that works, as push does not yield the desired result. constructor() { su ...

Using Next-Image Relative Paths can lead to 404 errors when being indexed by web crawlers

I have implemented next-image in my project, and all the images are hosted on Cloudinary. The images display correctly, but when I run a website analysis using tools like Screaming Frog, I receive numerous 404 errors. This is because the tools are looking ...

Using Axios to facilitate communication between API and Interface

I am facing a challenge in establishing communication between the API and the Interface. To explain further: I send a JSON file from the API, but I am unable to retrieve it and display it in the Interface. The JSON structure is simple: {"name": "joe"} My ...

Encountered an error in the React.js app where it cannot read the property 'Tag' of undefined from domhandler

I recently encountered an issue with my react.js project, which utilizes domhandler v4.2.0 through cheerio. Everything was running smoothly for months until one day, I started getting this error during the build process: domelementtype package includes a ...

Learn the process of retrieving JSON data in an Excel file using the json_to_sheet function

I am currently working on populating an excel file by utilizing the JSON data provided below. This JSON data is retrieved from an HTTP response and I intend to utilize it for downloading an excel file. { "dynaModel":[ { ...

When attempting to utilize nsIPrefBranch in a Firefox extension to save data, an unexpected error of NS_ERROR_UNEXPECTED occurs

I am facing a challenge with saving persistent data in a Firefox extension. Currently, I am attempting to utilize nsIPrefBranch in the following manner: var db = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.ns ...

Image uploading using AJAX onchange event

Is it possible to use AJAX to upload images when using the input onchange event? I've attempted various methods but none of them seem to be working. Here is the code I am currently using: $(document).ready(function (e) { $("#uploadForm").on(&apos ...

Extract hierarchical JSON data into a DataTable

I am facing a challenge in parsing JSON data that is nested into a datatable structure. Each group within the data contains 'attributes' field with inner data for Title, Value, and Priority. [{ "Title": "OVERVIEW", "Priority": 1, "attri ...

Show specific keys in the JSON response

Creating a straightforward API using express and sqlite, I aim to customize my GET request to only exhibit specific keys in each JSON object within the response. The snippet below showcases my current code: router.get('/cars', (req, res) => { ...