Google Chart API - using JS to dynamicaly add data - javascript

Morning, I have the data hidden in the page but im not sure how to add it to the addRows function.
This is what I have:
google.load("visualization", "1", {packages:["corechart"]});
$(document).ready(function(){
var rowArray = [];
$('input[name=device_name]').each(function(i){
var name = $(this).val();
var amount = $(this).next().val();
rowArray.push(["'" + name + "'", amount]);
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Device');
data.addColumn('number', 'Amount');
data.addRows( rowArray );
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, {
width: 600,
height: 340,
title: 'Handheld Device Usage',
hAxis: {
title: 'Mobile Device Name',
titleTextStyle: {
color: '#404040'
}
}
});
}
});
Can anyone see where im going wrong?
Regards,
Phil

Maybe this will work:
$('input[name=device_name]').each(function(i){
var name = $(this).val();
var amount = ($(this).next().val() * 1);
rowArray.push([name, amount]);
});

the problem is that amount is a string... I've seen that you're using a js framework so you could probably make a console.log(rowArray); to debug.
a good way to correct that would be if you change this:
var amount = $(this).next().val().toInt();
I've tested it http://jsfiddle.net/TfsFT/1/ and its working. Although i had to change a few things cause i was using Mootools.. and i didn't have the html code :P
Good Luck!

Related

how to read data from an JSON file and pass it to google chart rows (javascript)

have the following function JSONChart()
it reads json data from var "allText" and should be able to parse the data and use it as row data for google charts.
Commenting out the adding row part displays the column data correctly with empty graph.
Need a way to parse the given sample data from a file and display it as row data in the google chart.
function JSONChart() {
google.charts.load('current', {'packages':['corechart']});
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time stamp');
data.addColumn('number', 'CPU');
data.addColumn('number', 'MEMORY');
data.addColumn({type:'string', role:'annotation'});
data.addColumn({type:'string', role:'annotationText'});
var data1 = JSON.parse(allText);
var dataTableData = google.visualization.arrayToDataTable(data1);
data.addRows (dataTableData);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
// Set chart options
var options = {'title' : 'CPU & Memory',
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Percentage'
},
'width':1400,
'height':600,
curveType: 'function'
};
chart.draw(data, options);
}
window.onload = function() {
google.charts.setOnLoadCallback(JSONChart());
};
Sample JSON passed into variable "allText"
{"2017/11/03 01:06:51":{"SCREEN":" ABC ","MEMORY":" 32.0142% ","CPU":" 9.1% "},"2017/11/03 02:22:20":{"SCREEN":" XYZ ","MEMORY":" 31.101% ","CPU":" 10.3% "}
a few things...
1) arrayToDataTable expects a simple array, not a json object
it also returns an entire data table, which has already been created --> data
instead, convert each json object to an array,
then use addRows to add the data to the existing data table --> data
something like...
for (var date in data1) {
if (data1.hasOwnProperty(date)) {
chartData.push([
date,
parseFloat(data1[date].MEMORY.replace('%', '').trim()),
parseFloat(data1[date].CPU.replace('%', '').trim()),
data1[date].SCREEN,
'' // not sure what value you want to use here
]);
}
}
data.addRows(chartData);
2) google.charts.load -- this statement waits for the window / document to load, before calling the callback
no need for --> window.onload = function() {...
google.charts.load actually returns a promise,
so you can do something like...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
// draw chart code here...
3) when passing a callback function to setOnLoadCallback,
a reference to the function should be passed --> JSONChart
not the result of a function --> JSONChart() (remove parens)
4) recommend similar setup as following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time stamp');
data.addColumn('number', 'CPU');
data.addColumn('number', 'MEMORY');
data.addColumn({type:'string', role:'annotation'});
data.addColumn({type:'string', role:'annotationText'});
var chartData = [];
var data1 = {"2017/11/03 01:06:51":{"SCREEN":" ABC ","MEMORY":" 32.0142% ","CPU":" 9.1% "},"2017/11/03 02:22:20":{"SCREEN":" XYZ ","MEMORY":" 31.101% ","CPU":" 10.3% "}};
for (var date in data1) {
if (data1.hasOwnProperty(date)) {
chartData.push([
date,
parseFloat(data1[date].MEMORY.replace('%', '').trim()),
parseFloat(data1[date].CPU.replace('%', '').trim()),
data1[date].SCREEN,
'' // not sure what value you want to use here
]);
}
}
data.addRows(chartData);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
var options = {'title' : 'CPU & Memory',
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Percentage'
},
height: 600,
curveType: 'function'
};
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google charts javascript error

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);
}

Sending a "google.visualization.Table" via Email

I have a PHP script - in which I'm creating google.visualization.Table object in javascript.
I want to send the table created via Email - but for now the email is sent as empty...
EDIT:
<script type='text/javascript'>
google.load('visualization', '1', {packages:['table']});
google.setOnLoadCallback(drawTable);
var data;
function drawTable() {
data = new google.visualization.DataTable();
$datacols
data.addRows($alldata);
var table = new google.visualization.Table(document.getElementById('table_div'));
var formatter = new google.visualization.ColorFormat();
formatter.addRange(null, 0, 'red', null);
$formatcols
allowHtml=true;
var cssClassNames = { 'tableCell': 'mycell-td', 'headerCell': 'myhead-td gradient'};
table.draw(data, {allowHtml: true, width: '100%',showRowNumber: false, 'cssClassNames': cssClassNames});
document.getElementById('Download_CSV').style.visibility = \"visible\"; //Enable download CSV button when data is available
</script>
The script above is concatenated to a string with additional code, and then sent by email.
Does anyone know how can I do it?
Thank you!

Google Pie chart usage with Jquery inside a function?

I want to use google pie chart inside jquery and want the chart to be generated based on the condition.
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
var options = {title: 'Sample Chart'};
function drawChart() {
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'col1');
data1.addColumn('number', 'col2');
data1.addRow(["sample", 12]);
data1.addRow(["sample", 24]);
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data1, options);
}
Jquery function,
$.each(result, function(index) {
$("#tableContents").append("some html generation");
});
I want the data1 to be prepared during the loop of Jquery and draw at the end of the function. I see that if I takeout the data1 part of code (shown below) outside the function drawchart, I get
in console log,
Cannot read property 'DataTable' of undefined error
The data1 part of code I removed out of drawChart(),
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'col1');
data1.addColumn('number', 'col2');
data1.addRow(["sample", 12]);
data1.addRow(["sample", 24]);
Please help, thanks in advance.
You can parse the results into the DataTable like this:
function drawChart() {
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'col1');
data1.addColumn('number', 'col2');
$.each(result, function(index) {
$("#tableContents").append("some html generation");
// assumes results[index] has "col1Value" and "col2Value" properties
data1.addRow([results[index].col1Value, results[index].col2Value]);
});
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data1, options);
}

Passing values between two javascript in a html

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.

Categories

Resources