0

I am trying to make a Google chart which pulls the data from a hidden field on a web page.

If I add the data in directly via data.addRows it works fine:

google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
      var data = new google.visualization.DataTable();
      data.addColumn('date', 'Date');
      data.addColumn('number', 'Rainfall');     

      data.addRows([[new Date(2000, 8, 5), 56], [new Date(2000, 8, 6), 22], [new Date(2000, 8, 7), 44], [new Date(2000, 8, 8), 40], [new Date(2000, 8, 9), 62]]);

      var options = {
        title: 'Rainfall'
      };

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

However, if I try and create a string which contains the array and then add it using addRows it doesn't work:

google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
      var data = new google.visualization.DataTable();
      data.addColumn('date', 'Date');
      data.addColumn('number', 'Rainfall');     

      var myData = "[[new Date(2000, 8, 5), 56], [new Date(2000, 8, 6), 22], [new Date(2000, 8, 7), 44], [new Date(2000, 8, 8), 40], [new Date(2000, 8, 9), 62]]"

      data.addRows(myData);

      var options = {
        title: 'Rainfall'
      };

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

How can I add the data in the string to the DataTable?

JSFiddle: https://jsfiddle.net/oo5w6ghf/4/

1 Answer 1

1

Figured it out - I need to add "eval" to the string:

 var myData = eval("[[new Date(2000, 8, 5), 56], [new Date(2000, 8, 6), 22], [new Date(2000, 8, 7), 44], [new Date(2000, 8, 8), 40], [new Date(2000, 8, 9), 62]]")
Sign up to request clarification or add additional context in comments.

1 Comment

So long as you're aware of the advice against using eval and are happy to take on those risks, it's fine. I don't see any other way immediately of doing this, but you just need to realize that using eval is like juggling a running chainsaw - fine if you know what you're doing and can control your environment. Dangerous and bloody otherwise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.