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>
Related
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>
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>
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);
}
I am working on a UI where a user chooses both a start and end dates in order to retrieve data. Some of these data are shown in tables and I want to show a google chart related to those data displayed.
When the user finally chooses the dates, i send these two variables by using the $.post() function as follows:
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['corechart']}]}"></script>
$('#button-send').click(function() {
var url_route = "{{URL::action('Controller#general_stats_post')}}";
var start_date=$('#start_date_i').val();
var end_date=$('#end_date_i').val();
var datos = {start_date: start_date, end_date:end_date,_token:_token};
Once the send button is clicked, i use the $.post() function which works fine:
$.post(url_route, datos, function(data,status){
if(status=='success'){
console.log('Dates sent successfully. Now the data retrieved are: '+data);
var response = jQuery.parseJSON(data);
if(response.events_types.length === 0){
console.log('events_types is empty.');
}
else{
console.log('The string for google charts got is: `'+response.events_types+'`');
/*Here goes the google chart*/
}
}else if(status=='error'){
console.log('Errors found');
}
});//end of .post() function
}); //end of onclick button-send
The events_types string is, for example:
[['Event','Total'],['Workshop',1],['Seminar',1]]
which perfectly works in google's jsfiddles.
So, what i have been trying is to put the google chart's drawChart() function inside the {} where the string events_types does exist as follows:
$.post(url_route, datos, function(data,status){
if(status=='success'){
console.log('Dates sent successfully. Now the data retrieved are: '+data);
var response = jQuery.parseJSON(data);
if(response.events_types.length === 0){
console.log('events_types is empty.');
}
else{
console.log('The string for google charts got is: `'+response.events_types+'`');
/*GOOGLE CHART*/
google.setOnLoadCallback(drawChart);
function drawChart() {
console.log('Inside the drawChart() function');
var data = google.visualization.arrayToDataTable(response.events_types);
var options = {
title: 'My test'
};
var chart = new google.visualization.PieChart(document.getElementById('eventos_charts'));
chart.draw(data, options);
}
/*END OF GOOGLE CHART PART*/
}
}else if(status=='error'){
console.log('Errors found');
}
});//end of .post() function
}); //end of onclick button-send
I have put a console.log message to let me know that the drawChart() has been run. However, I never get that message. So this means the drawChart() function is never run :/ I am stuck.
Almost working - EDIT
This is the code that is working... but only if I define the data string manually, that is to say:
else{
console.log('The data string is: `'+response.tipos_eventos+'`');
var the_string=response.tipos_eventos;
/***** start Google charts:*******/
//google.setOnLoadCallback(drawChart);
function drawChart() {
console.log('Inside the drawChart() function');
var data = google.visualization.arrayToDataTable([['Evento','Cantidad'],['Taller',1],['Seminario',1]]);//DEFINED MANUALLY
var options = {
title: 'The chart'
};
var chart = new google.visualization.PieChart(document.getElementById('events_types'));
chart.draw(data, options);
}
drawChart();//Thanks to #FABRICATOR
/**** END Google charts: Events types *********/
}
However, if i tried to get the data dynamically:
else{
console.log('The data string is: `'+response.tipos_eventos+'`');
var the_string=response.tipos_eventos;
/***** start Google charts:*******/
//google.setOnLoadCallback(drawChart);
function drawChart() {
console.log('Inside the drawChart() function');
var data = google.visualization.arrayToDataTable(the_string);//DEFINED DYNAMICALLY
var options = {
title: 'The chart'
};
var chart = new google.visualization.PieChart(document.getElementById('events_types'));
chart.draw(data, options);
}
drawChart();//Thanks to #FABRICATOR
/**** END Google charts: Events types *********/
}
I get the following error:
Uncaught Error: Not an array
Any ideas to make it work? What am I missing?
Finally I have found the easiest solution.
Given that I am using Laravel's ORM (Illuminate/Database), the gotten data comes in json format.
This works for Laravel and Slim framework.
So I pass the variables directly to the view (in Slim):
$app->render('home.php',[
'myArray'=>$myArray
]);
Then, inside the view (in this case, Twig view. It should be similar in blade), I get the array and put it in a variable inside the Javascript code:
var myArray = {{ myArray|json_encode|raw }};
Then I iterate to get each element and add it into the Google chart data array:
$.each(myArray,function(index, value){
//console.log('My array has at position ' + index + ', this value: ' + value.r1);
data.addRow([value.col1,value.col2,value.col3,value.col4]);
});
And it works now.
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.