I can't see what i'm missing. I can't seem to get the Google chart api running with a little bit of ajax. What am I doing wrong?
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var dataSet = $.ajax({
url: "phpdata.php",
async: false
}).responseText;
var data = google.visualization.arrayToDataTable([
dataSet
]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
my php data:
['year', 'fixedassets'],
['2009', 1],
['2010', 1.2],
['2011', 1.6]
I don't know if it would solve your issue, I was facing a similar issue while rendering partials called from ajax calls. The drawChart function was not being called which basically meant that the setOnLoadCallback was not firing as expected. To overcome that, I modified my calls as follows:
google.load("visualization", "1", {packages:["corechart"]});
//google.setOnLoadCallback(drawChart);
$(function() {
drawChart(); //works
});
function drawChart() {
}
So basically I left the google method , and made my own self calling function which gets called whenever the page renders or the div is updated.
The problem is likely with your ajax call:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var dataSet = [ ['year', 'fixedassets'],['2009', 1],['2010', 1.2],['2011', 1.6]];
var data = google.visualization.arrayToDataTable(dataSet);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
This works, so it's not a problem with any of the existing code. Your format for the ajax call is using a bunch of depreciated jQuery calls, and without access to your server I can't test it, but you could try something like:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
$.get("phpdata.php", function(response_data) {
var data = google.visualization.arrayToDataTable([response_data]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
and see if that works.
I think that the problem you're having is that you have a string: "['year', 'fixedassets'], ['2009', 1], ['2010', 1.2], ['2011', 1.6]" and you want it evaluated as an array: [['year', 'fixedassets'],['2009', 1],['2010', 1.2],['2011', 1.6]]. The easy-but-insecure way to solve this is to use eval(). you'd say:
$.get("phpdata.php", function(response_data) {
var data = google.visualization.arrayToDataTable(eval('[' + response_data + ']');
This is not-great-but-working as long as you completely control the server, and you're not getting any user input that could be sent from your server.
The 'right' way to do this would be to send actual json from your server, instead of sending what you're sending, and then use JSON.parse(response_data).
Related
I am trying to visualize data from a javascript file as shown below.
data = [ ['Year','China','India'],
['C1960',1.83286768126466,1.96098348563911],
['C1961',-1.01552778731319,1.99843774000741],
['C1962',0.820455548748518,2.03190545392019],
.
.
.
['C1963',2.45764740395145,2.0569116837358],
['C2017',0.559121331017265,1.06259739387194],
['C2018',0.455899678672578,1.03732336037888],
['C2019',0,0]
];
The html code I am using is as below.
<html>
<head>
<script type="text/javascript" src="data.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable( data );
var options = {
title: 'World Bank Data Visualization',
chartArea: {left:'10%',top:'10%', width: '65%', height: '65%'}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 1300px; height: 600px;"></div>
</body>
</html>
I am getting the error as
Uncaught (in promise) Error: Data for arrayToDataTable is not an array.
at Object.gvjs_ll [as arrayToDataTable] (jsapi_compiled_default_module.js:188)
at drawChart (data.htm:9)
Can anyone help me please? When I am loading another javascript file like this, it perfectly works. I don't know what is wrong with my code.
In your html, you have a variable named data. Due to this, the variable data from data.js is shadowed. More detail about Variable Shadowing here.
To make your code work, change that variable name to something else.
Something like:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var dataVis = google.visualization.arrayToDataTable( data );
var options = {
title: 'World Bank Data Visualization',
chartArea: {left:'10%',top:'10%', width: '65%', height: '65%'}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(dataVis, options);
}
I had a deep look at somewhat similar questions asked here and here. I tried their implementation. It didn't work !
Then I had a look at following link by Google : tow charts in one page. Followed the same procedure but still ended up showing only one chart at a time.
Below is my code :
<script type = "text/javascript" src = "https://www.google.com/jsapi" ></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<!--Load the Ajax API-->
<script type="text/javascript">
google.load("visualization", "1", {packages:["line"]});
google.setOnLoadCallback(drawChart);
google.setOnLoadCallback(drawOutputChart);
function drawChart() {
var data = new google.visualization.DataTable(<?= $jsonAnalogTable ?>);
var options = {
chart: {
title: ' Data ',
is3D: 'true'
},
width: 550,
height: 350,
};
var chart = new google.charts.Line(document.getElementById('analogchart'));
chart.draw(data, options);
}
function drawOutputChart(){
var data2 = new google.visualization.DataTable(<?= $jsonOutputTable ?>);
var options2 = {
chart: {
title: ' Data ',
is3D: 'true'
},
width: 550,
height: 350,
};
var chart2 = new google.charts.Line(document.getElementById('outputChart'));
chart2.draw(data2, options2);
}
</script>
**HTML Code to call it : **
<table>
<tr>
<td>
<div id="analogchart" >
</div>
</td>
<td>
<div id="outputChart" >
</div>
</td>
</tr>
</table>
I seriously have no idea what is going wrong as it is able to show one chart at a time, but not both !
it is recommended to use loader.js vs. the older library jsapi
and don't need both for a Line chart
also, setOnLoadCallback should only be called once per page
which can be included in the load statement, as in the following example
try something like this...
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
callback: function () {
drawChart();
drawOutputChart();
},
packages: ['line']
});
function drawChart() {
var data = new google.visualization.DataTable(<?= $jsonAnalogTable ?>);
var options = {
chart: {
title: ' Data ',
is3D: 'true'
},
width: 550,
height: 350,
};
var chart = new google.charts.Line(document.getElementById('analogchart'));
chart.draw(data, options);
}
function drawOutputChart(){
var data2 = new google.visualization.DataTable(<?= $jsonOutputTable ?>);
var options2 = {
chart: {
title: ' Data ',
is3D: 'true'
},
width: 550,
height: 350,
};
var chart2 = new google.charts.Line(document.getElementById('outputChart'));
chart2.draw(data2, options2);
}
</script>
I have data in a path static/data.json.I am trying to plot chart using google charts.I want to take out data in data.json file and use it for google charts.
data.json is given below
data = '[{"k": "RAM" , "v":0.515625},{"k": "Camera" , "v":0.515625},{"k": "Design" , "v":0.05},{"k": "Processor" , "v":0},]';
my html code is in template/isworked.html.
Below code is isworked.html
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="application/json" src="static/d.json"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
var mydata = JSON.parse(data);
function drawChart() {
// Create the data table.
//loading data from json
var data = new google.visualization.DataTable();
data.addColumn('string', 'Feature');
data.addColumn('number', 'Positive');
var f,n;
for(var i = 0 ; i<data.length;i++){
f = data[i].k
n = data[i].v
data.addRows([[f,n]])
}
// Set chart options
var options = {'title':'Pie Chart',
'width':800,
'height':700};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
I am not able to plot graph.
This data.json is generated from a python script. I am running everyting using flask framework in Ubuntu
I have no experience in this topic. Can anybody help me?
UberKaeL is correct.
update:
corrected multiple problems with the code and data, e.g., the trailing comma in the data. It works now ... click the "Run Code Snippet" button.
"mydata" is the problem. You are attempting to use data before the json file has loaded. That triggers the error. And mydata is not used for anything. You also need to add a DIV to hold the pie chart. The code snippet below works, but the json data is incorrect for drawing a pie chart. Correct the data and it should work for you.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var mydata = [{"k": "RAM" , "v":0.515625},{"k": "Camera" , "v":0.515625},{"k": "Design" , "v":0.05},{"k": "Processor" , "v": 0}];
</script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Feature');
data.addColumn('number', 'Positive');
var f,n;
for(var i = 0 ; i<mydata.length;i++){
f = mydata[i].k
n = mydata[i].v
data.addRows([[f,n]])
}
var options = {'title':'Pie Chart', 'width':800, 'height':700};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
After a while it seems like your page runs the code before loading the json file. Reading json like that is not a good practice, is better to do an AJAX request like jQuery.getJSON()
so if your are using jQuery do this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON</title>
</head>
<body>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
var mydata=jQuery.getJSON("static/d.json");
if(mydata) {
alert("yay worked");
}
else {
alert("something is wrong");
}
//rest of your code
//function drawChart() { ...
</script>
</body>
</html>
Also is a good practice to enclose your program inside a $(document).ready and remember to remove last comma in your JSON:
data = '[{"k": "RAM" , "v":0.515625},{"k": "Camera" , "v":0.515625},{"k": "Design" , "v":0.05},{"k": "Processor" , "v":0}]';
#Robert gives you a good answer about how to draw the chart
You are not using mydata where you put json read values.
data contains an empty new google.visualization.DataTable() and the loop are reading values from it, not from mydata.
I'm trying to load php array inside native javascript method of gwt application using ajax and display google chart. But it does not give required output...below are my codes
Server side:
$data = array();
$data [] = array("Name", "Value");
$data [] = array("PHP", 78);
$data [] = array("JAVA", 10);
$data [] = array("HTML", 120);
$table = json_encode($data);
echo $table ;
?>
Client side:
<html>
<head>
<title>Graph</title>
<!-- Load jQuery -->
<script type="text/javascript" language="javascript" src="ajax/ajax.nocache.js"></script>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<!-- Load Google JSAPI -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {'packages' : ["corechart"] });
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
Native javascript method
private native void generateGraph()
/*-{
$wnd.google.load("visualization", "1", {
packages : [ 'corechart' ],
callback : drawChart
});
function drawChart() {
var jsonData = $.ajax({
url: "http://localhost:8080/Ajax/get_json.php",
dataType: "json",
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData);
var data = new $wnd.google.visualization.arrayToDataTable(obj);
var options = {
title: 'Graph'
};
var chart = new $wnd.google.visualization.LineChart(
$wnd.document.getElementById('chart_div'));
chart.draw(data, options);
}
}-*/;
thanks for reply!!!
I'm using the following Script:
<header>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
</header>
<body>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Header');
data.addColumn('number', '');
data.addColumn('number', '');
data.addRows([
['Monday',300,43],
['Tuesday',250,545],
['Wednesday',122,78],
['Thursday',348,92],
['Friday',23,61],
['Saturday',39,93]
]);
var options = {
title: '',
hAxis: {title: '', titleTextStyle: '#efede9'},
backgroundColor: '#efede9',
legend: 'none'
};
var chart = new google.visualization.AreaChart(document.getElementById('area_chart_google'));
chart.draw(data, options);
}
</script>
<div id="area_chart_google" class="area-chart"></div>
<body>
I cannot use the script inside Header because I'm using dynamic content.
I figure it out to work when I first load the page, and after refreshing it. My problem now is that I'm using a select menu with an onchange event, similar to this:
<select id="form_frame1" name="frame1" onchange="getChart(this);">
<option value="area_chart_google" >Area Chart</option>
<option value="area_chart_2" selected="selected">Stacked Chart</option>
</select>
My getChart function is:
function getChart(selection) {
if (selection.value == "area_chart_2") {
document.getElementById('area_chart_2').style.display = 'block';
document.getElementById('area_chart_google').style.display = 'none';
}
else {
document.getElementById('area_chart_2').style.display = 'none';
document.getElementById('area_chart_google').style.display = 'block';
}
}
So, once my area_chart_google is not displayed (display: none) and I select it, I get the error:
*Firebug* google-visualization-errors-all-1
*Chrome* Cannot read property 'length' of null
*Safari* 'null' is not an object
I guess is something with getElementById, so I tried using:
window.onload = function(){ javascript code here }
And also:
$(document).ready(function() {
javascript code here
});
Nothing happen. I get no error but the Chart don't appear.
Any help will be highly appreciated.
This is working for me:
function getChart(selection) {
if (selection.value == "area_chart_2") {
document.getElementById('area_chart_2').style.display = 'block';
document.getElementById('area_chart_google').style.display = 'none';
}
else {
document.getElementById('area_chart_2').style.display = 'none';
document.getElementById('area_chart_google').style.display = 'block';
drawChart(); //call this function when using this Google Chart
}
}
You need to load the Google API first:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
You also should have proper <body> and <head> tags in your script.
Otherwise the code is fine. The below works fine for me:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Google Visualization API Sample
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Header');
data.addColumn('number', '');
data.addColumn('number', '');
data.addRows([
['Monday',300,43],
['Tuesday',250,545],
['Wednesday',122,78],
['Thursday',348,92],
['Friday',23,61],
['Saturday',39,93]
]);
var options = {
title: '',
hAxis: {title: '', titleTextStyle: '#efede9'},
backgroundColor: '#efede9',
legend: 'none'
};
var chart = new google.visualization.AreaChart(document.getElementById('area_chart_google'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="area_chart_google" class="area-chart"></div>
</body>
</html>
not sure, but try doing :
google.load("visualization", "1", {packages:["corechart"]});
//..your drawChart() function code here
$(document).ready(function() {
google.setOnLoadCallback(drawChart);
});
I hope you have already included following script in your header:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>