I'm trying to display a google pie chart from data recovered from excel sheet.
The returned String is described below which I'm passing in google.visualization.arrayToDataTable();
The code that I have used is:
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
var str = '<%= JSNstring %>'; //returned string 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>
This is showing error :
JavaScript runtime error: First row is not an array.
Please tell me what I'm doing wrong and how to correct it.
Thanks in advance.
`document.write(ss);`
Is only for this example, right? If it not so remove it and try to see inside your function what is the value of ss, 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 to rewrite your function drawChart() like this-
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 created for you jsfiddle here jsfiddle, with your array in hard code, as you can see it is working here.So your problem is something with the server side or with the value of ss.
I think you need to parse the string into an array, try this...
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
var str = '<%= JSNstring %>'; //returned string from C#.
var res= str.replace(/""/g,"'");
res=res.replace(/"/g,"'");
var ss='[' + res + ']';
function drawChart() {
var data = google.visualization.arrayToDataTable(eval(ss));
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
Related
Currently, I'm trying to update the value of my Google Line Chart. My aim is to update it periodically, so that I can obtain the result of a dynamic chart. Right now I need to refresh the whole page, but this is not a good solution.
I tried with setTimeout() function, but recalling the function drawChart() doesn't seem to be working. Here is my JavaScript code:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
// The intervals data as narrow lines (useful for showing raw source data)
var options = {
title: 'Valores de LDR1',
vAxis: { ticks: [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]},
curveType: 'function',
lineWidth: 4,
legend: 'none'
}
var ldr1 = new google.visualization.LineChart(document.getElementById('ldr1'));
var ldr2 = new google.visualization.LineChart(document.getElementById('ldr2'));
var ldr3 = new google.visualization.LineChart(document.getElementById('ldr3'));
var ldr4 = new google.visualization.LineChart(document.getElementById('ldr4'));
var data = google.visualization.arrayToDataTable(<?php prueba('ldr1') ?>);
var data2 = google.visualization.arrayToDataTable(<?php prueba('ldr2') ?>);
var data3 = google.visualization.arrayToDataTable(<?php prueba('ldr3') ?>);
var data4 = google.visualization.arrayToDataTable(<?php prueba('ldr4') ?>);
ldr1.draw(data, options);
options["title"] = "Valores de LDR2";
ldr2.draw(data2, options);
options["title"] = "Valores de LDR3";
ldr3.draw(data3, options);
options["title"] = "Valores de LDR4";
ldr4.draw(data4, options);
updateChart();
setTimeout(drawChart, 1000);
}
The php code get values from the database, so as I see it, I only have to repeat the code of the function drawChart(), but this doesn't happen.
I am trying to create a Google Annotation chart by loading some data from a CSV file using the example found here:
https://developers.google.com/chart/interactive/docs/gallery/annotationchart
I've tried to modify the code (using my limited JS knowledge) to load from a CSV file but I'm getting no graph.
My code so far:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type='text/javascript'>
google.charts.load('current', {'packages':['annotationchart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
$.get('test.csv', function(csvString)
{
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
arrayData = arrayData.map(function (row)
{
return
[new Date(row[0]),row[1]];
});
var data = google.visualization.arrayToDataTable(arrayData);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
var options = {
displayAnnotations: true
};
chart.draw(data, options);
}
}
</script>
</head>
<body>
<div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>
CSV File
Date,Value1
2014-01-01,1233
2014- 01-02,1334
2014-01-03,1488
2014-01-04,1888
2014-01-05,2011
2014-01-06,1900
2014-01-07,1768
2014-01-08,2345
first, add jquery and jquery csv to your page.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
then replace the code as follows.
see comments for explanations...
// load google charts
google.charts.load('current', {
packages: ['annotationchart']
}).then(function () {
// declare data variable
var arrayData;
// get csv data
$.get('test.csv', function(csvString) {
// get csv data success, convert to an array, draw chart
arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
drawChart(arrayData);
}).fail(function () {
// get csv data failed, draw chart with hard-coded data, for example purposes
arrayData = [
['Date','Value1'],
['2014-01-01',1233],
['2014-01-02',1334],
['2014-01-03',1488],
['2014-01-04',1888],
['2014-01-05',2011],
['2014-01-06',1900],
['2014-01-07',1768],
['2014-01-08',2345],
];
drawChart(arrayData);
});
});
// draw chart
function drawChart(arrayData) {
// convert string in first column to a date
arrayData = arrayData.map(function (row) {
return [new Date(row[0]),row[1]];
});
// create google data table, chart, and options
var data = google.visualization.arrayToDataTable(arrayData);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
var options = {
displayAnnotations: true
};
// draw chart
chart.draw(data, options);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
note: you can remove the fail callback, it is for example purposes here on stack overflow...
You need to follow 3 step for this task
Fire ajax request and take csv data
Convert csv data into array
Pass csv array in google graph
Please take refrence from following example:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type='text/javascript'>
//Step 1: Get string from csv
$(document).ready(function () {
$.ajax({
type: "GET",
url: "test.csv",
dataType: "text",
success: function (data) {
//Step 2: Convert "," seprated string into array
let arrData = csvToArray(data);
//Step 3: call chart with array data
callChart(arrData);
}
});
});
//convert csv string into array function
function csvToArray(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i = 1;i < allTextLines.length;i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j = 0;j < headers.length;j++) {
tarr.push(headers[j] + ":" + data[j]);
}
lines.push(tarr);
}
}
return lines;
}
function callChart(arrData) {
google.charts.load('current', { 'packages': ['annotationchart'] });
google.charts.setOnLoadCallback(function () { drawChart(arrData); });
}
function drawChart(arrData) {
var data = new google.visualization.DataTable();
//Step 4: add csv your column
data.addColumn('date', 'Date');
data.addColumn('number', 'Kepler-22b mission');
//Step 5: pass your csv data as array
data.addRows(arrData);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
var options = {
displayAnnotations: true
};
chart.draw(data, options);
}
</script>
</head>
<body>
<div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>
I am using google pie chart my json value is:
[
["Exhibitor Fee", 21],
["Attendee Registration", 400],
["Hotel Cost Per Night", 21212],
["Sponsorship", 435],
["Shippng", 456]
]
And my code is:
var jsonValues = '<?php echo $staticEvent; ?>'
var pieValues = $.parseJSON(jsonValues);
console.log(pieValues);
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(pieValues);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
by the looks of things here the pie chart expects the first array to be the headers for your chart, which i would imagine should be strings, whereas your first array is string, int
Try changing your json to:
[
["Activity", "Cost"],
["Exhibitor Fee", 21],
["Attendee Registration", 400],
["Hotel Cost Per Night", 21212],
["Sponsorship", 435],
["Shippng", 456]
]
how are you,
Try it:
in your php var $staticEvent; you change to:
<?php
$staticEvent = json_encode($staticEvent, JSON_UNESCAPED_UNICODE);
?>
And your JS:
var jsonValues = '<?php echo $staticEvent; ?>';
var pieValues = $.parseJSON(jsonValues);
console.log(pieValues);
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(pieValues);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
I'm trying to dynamically render a google visualization chart with an AJAX call in flask to set the data. User enters input then clicks a link which calls the ajax function to get the data. the "/ajax_test" view will return a json object but the problem I have is i don't know how to correctly pass the data back into the DataTable function. How do i pass the json data i'm getting from ajax to a variable for the drawchart function?
Chart function:
<script type="text/javascript">
function drawChart(){
var data = new google.visualization.DataTable(jsondata);
var options = {
explorer: {},
}; //end options
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Ajax function:
<script type=text/javascript>
$(function() {
$('a#DrawChart').bind('click', function() {
$.getJSON($SCRIPT_ROOT + '/ajax_test',
{//input data sent to view}
, function(data) {
var jsondata = data.test_json;
drawChart();
});
return false;
});
});
</script>
This method doesn't know where jsondata comes from:
function drawChart() {
var data = new google.visualization.DataTable(jsondata);
...
}
Add jsondata as a parameter:
function drawChart(jsondata) {
var data = new google.visualization.DataTable(jsondata);
...
}
And then in your Ajax call pass jsondata to the method:
function(data) {
var jsondata = data.test_json;
drawChart(jsondata);
}
I have done something similar using the following code, this is a jinja2 example, so you have do adapt your code (change the way jsonData var is initialized):
<script type="text/javascript">
//load the Google Visualization API and the chart
google.load('visualization', '1', {'packages': ['corechart']});
google.setOnLoadCallback (createChart);
var jsonData = {{ value_columns | tojson | safe }}
function createChart() {
var dataTable = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.LineChart(document.getElementById('chart'));
//define options for visualization
var options = {is3D: 'no', title: 'Some Title' };
attachRedrawForTab(chart, dataTable, options);
attachRedrawForAccord(chart, dataTable, options);
//draw our chart
chart.draw(dataTable, options);
}
</script>
I have a case where i need to load a char based on the input from another javascript. But it doesn't work in my case. I have added the code below:
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart', 'table']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var json = $.ajax({
url: fileURL, // make this url point to the data file
dataType: 'json',
cahce:false,
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(json);
var options = {
title: graphTitle,
is3D: 'true',
width: 800,
height: 600
};
var tableOptions = {
title: 'App Listing'
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
and I pass the value for graphtitle and fileURL as below:
<script type="text/javascript">
$(document).ready(function () {
var fileURL = "";
var graphTitle = "";
function showDiv() {
if($firstCheck) {
var selText;
$("#dd4 li a").show(function () {
selText = $(this).text();
});
if(selText !== "Factor"){
if(selText == "IA Architecture Usage"){
fileURL = "get_json.php";
graphTitle = "IA Architecture Variation";
}else if(selText == "Tablet to Phone"){
fileURL = "get_tablet_support.php";
graphTitle = "Tablet Usage Variation";
}
document.getElementById('chart_div').style.display = "block";
}
}else{
document.getElementById('chart_div').style.display = "none";
}
}
</script>
Both these javascript are within the same file. I can't pass the fileURL and graphTitle when I used the above code. Any idea how to solve this issue?
Use global variables with window. E.g.
$(document).ready(function () {
window.fileURL = "";
window.graphTitle = "";
});
Don't specify "var" or it will only be within the scope of the function.
EDIT: Also make sure that the script in which your variables are assigned initially is before the other one.
How about something a bit more OO oriented (not really OO, but less inline code) ? It's cleaner and easier to read/maintain ..example could still use some work, but i"m sure you get the idea.
function loadChart(title, url) {
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart', 'table']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var json = $.ajax({
url : url, // make this url point to the data file
dataType: 'json',
cahce : false,
async : false
});
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(json);
var options = {
title : title,
is3D : 'true',
width : 800,
height: 600
};
var tableOptions = {
title: 'App Listing'
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
}
$(document).ready(function () {
var fileURL = "";
var graphTitle = "";
function showDiv() {
if($firstCheck) {
var selText;
$("#dd4 li a").show(function () {
selText = $(this).text();
});
if(selText !== "Factor") {
if(selText == "IA Architecture Usage"){
fileURL = "get_json.php";
graphTitle = "IA Architecture Variation";
} else if(selText == "Tablet to Phone"){
fileURL = "get_tablet_support.php";
graphTitle = "Tablet Usage Variation";
}
document.getElementById('chart_div').style.display = "block";
}
} else {
document.getElementById('chart_div').style.display = "none";
}
loadChart(graphTitle, fileURL);
}
}
btw i think you have an error in your code: .responseText seems pretty useless to me, and most likely throws an error in itself. Also i have no idea who is calling showDiv() in the code. From the example, i'd say it never fires.