I've queried my database for creating a dataset for a Google Pie Chart but I'm unable to create the column label which should be the month name.
JAVASCRIPT
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width:400, height:240});
}
PHP:
$sql = "SELECT COUNT(*) FROM `ldpage` WHERE YEAR(`frm_date`) = 2015 GROUP
BY month(`frm_date`)";
if (!mysql_query($sql,$connection)){
die('Error: ' . mysql_error());
}
print json_encode($sql);
The error shows "Table has no columns."
How should I create a label "months" for the rows"counts in the month".
Seems like you could modify your SQL to...
SELECT
month(`frm_date`),
COUNT(*)
FROM
`ldpage`
WHERE
YEAR(`frm_date`) = 2015
GROUP BY
month(`frm_date`)
You also need to have column headings when creating a DataTable.
Where you have...
var data = new google.visualization.DataTable(jsonData);
Try...
var data = new google.visualization.DataTable({
cols: [
{
label: 'Month',
type: 'number'
},
{
label: 'Count',
type: 'number'
}
]
});
data.addRows(jsonData);
Related
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'api/v1/readings',
data: { get_param: 'readings' },
dataType: 'json',
success: function (data) {
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var readings = data.readings;
function drawChart() {
var chartdata = new google.visualization.DataTable();
chartdata.addColumn('datetime', 'Time of Day');
chartdata.addColumn('number', 'Glucose Value');
chartdata.addRows([
readings.forEach(function(item){
let date = new Date(item.time);
{ [[`Date(${date.getYear()}, ${date.getMonth()}, ${date.getDate()})`], item.glucose_value]}
})
]);
So Im trying to pass a datestring from JSON readings to google charts api but im receiving a an error for every row must be a null or array.
the doc https://developers.google.com/chart/interactive/docs/datesandtimes#datestring states that dates must be passed in quotes so how do i pass my Date variable into the the string in order to parse it into a datetime object for the chart?
Your passing it as a object : {}
Take out the object notation and pass as [ [] ]
I am working on a web application which retrieves JSON data from servlet and uses it to generate chart. I am successful in retrieving the requisite json file in Google Chart compliant JSON format but am unable to generate the chart.
The jsbin of google chart is in the foll link: http://jsbin.com/hofaqidape/1/watch?html,js,output
The data var should be generated using JSON and I am doing the following stuff in my servlet
response.setContentType("application/json");
String json;
newClass s =new newClass();
List<newClass> classes = new ArrayList<newClass>();
s.setCount(1);
s.setName("Name");
classes.add(s);
s =new newClass();
s.setCount(2);
s.setName("Name1");
classes.add(s);
s =new newClass();
s.setCount(3);
s.setName("Name2");
classes.add(s);
s =new newClass();
s.setCount(1);
s.setName("Name4");
classes.add(s);
json="{ cols :[ { label : name , type : string },{ label : count , type : number }], rows :[";
String ss;int y;
for(newClass class1:classes)
{
ss=class1.getName();
y=class1.getCount();
json+="{ c : [{ v : "+ss+" },{ v : "+y+"}]},";
}
json=json.substring(0, json.length()-1);
json+="]}";
JSONObject js=null;
try {
js = new JSONObject(json);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
out.print(js);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
on the html side I have the foll code for my chart generation:
$(document).ready(function(){
$.ajax({
url : "Serv",
dataType: 'json',
contentType: 'application/json',
success : function(result) {
var dat=result;
alert(JSON.stringify(dat));
google.load('visualization', '1', {
packages: ['corechart', 'bar']
});
google.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable(dat);
var options = {
title: 'Motivation Level Throughout the Day',
hAxis: {
title: 'Name'
},
vAxis: {
title: 'Count'
}
};
var chart = new google.visualization.ColumnChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
},
complete: function()
{
alert('done');
}
});
});
alert(JSON.stringify(dat)) gives the alert as
{"cols":[{"label":"name","type":"string"},{"label":"count","type":"number"}],"rows":[{"c":[{"v":"Name"},{"v":1}]},{"c":[{"v":"Name1"},{"v":2}]},{"c":[{"v":"Name2"},{"v":3}]},{"c":[{"v":"Name4"},{"v":1}]}]}
which is a valid JSON.
how do I generate the chart using this data just like I did in jsbin?
google.setOnLoadCallback() set up a callback function to execute when Google Visualization API loaded, so google.load needs to load from the front explicitly. I am recalling it when i worked on them lately. My recommendation would be to move google.load and drawBasic() outside from AJAX call and use them in success of call, like this...
$(document).ready(function(){
google.load('visualization', '1', {
packages: ['corechart']
});
function drawBasic(d) {
var data = new google.visualization.DataTable(d);
var options = {
title: 'Motivation Level Throughout the Day',
hAxis: {
title: 'Name'
},
vAxis: {
title: 'Count'
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
$.ajax({
url : "Serv",
dataType: 'json',
contentType: 'application/json',
success : function(result) {
google.setOnLoadCallback(drawBasic(JSON.stringify(result)));
},
complete: function(){
// whatever..
}
});
});
Update: You only need to specify packages: ['corechart'] which will define most basic charts, including the pie, bar, and column charts.
finally got the answer to this question.
removed google.setOnLoadCallback() and called drawBasic() function from ajax call itself. somehow setOnLoadCallback() and $(document).ready() doesnt seem to coexist.
working code:
<script>
google.load('visualization', '1', {
packages: ['corechart']
});
function drawBasic(d) {
var data = new google.visualization.DataTable(d);
var options = {
title: 'Sample Data',
hAxis: {
title: 'Name'
},
vAxis: {
title: 'Count'
},
width: 600,
height: 240
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
$(function(){
$("#dd").change(function(){
if($(this).val()!='null')
{
$.ajax({
url : "Serv",
data: {dd1:$(this).val()},
dataType: 'json',
contentType: 'application/json',
success : function(result) {
drawBasic(result);
},
complete: function(){
// whatever..
}
}) ;
}
else
{
$("#chart_div").empty();
alert('please select');
}
});
});
</script>
I am trying to display 2 Google Graphs on my web page. Currently I can display the one without a problem.
The trouble comes in when I'm trying to display the other graph under the first one.
my front end code looks like this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', { packages: ['corechart'] });
</script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: 'MindYourMatterDash.aspx/GetData',
data: '{}',
dataType: "json",
success:
function (response) {
drawVisualization(response.d);
},
error: function (result) {
console.log(result);
alert("Please Contact Support with the following code in the subject :404 graph");
}
});
})
function drawVisualization(dataValues) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Column Name');
data.addColumn('number', 'Column Value');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].ColumnName, dataValues[i].Value]);
}
new google.visualization.PieChart(document.getElementById('visualization')).
draw(data, { title: "Broken PTP's Graph" });
}
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: 'MindYourMatterDash.aspx/GetDataFollowing',
data: '{}',
dataType: "json",
success:
function (response) {
drawVisualization(response.d);
},
error: function (result) {
console.log(result);
alert("Please Contact Support with the following code in the subject :404 graph");
}
});
})
function drawVisualization2(dataValues) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Column Name');
data.addColumn('number', 'Column Value');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].ColumnName, dataValues[i].Value]);
}
new google.visualization.PieChart(document.getElementById('FollowGraph')).
draw(data, { title: "Follow Ups Graph" });
}
</script>
and the code behind the page:
[WebMethod]
public static List<Data> GetData()
{
string cat = "";
int val = 0;
DataTable dt = new DataTable();
cQuery _GraphInfo = new cQuery();
_GraphInfo.Sqlstring = "SQL Statement";
DataSet ds = _GraphInfo.SelectStatement();
dt = ds.Tables[0];
List<Data> datalist = new List<Data>();
foreach (DataRow dr in dt.Rows)
{
cat = dr[0].ToString();
val = Convert.ToInt32(dr[1]);
datalist.Add(new Data(cat, val));
}
return datalist;
}
[WebMethod]
public static List<Data> GetDataFollowing()
{
string cat = "";
int val = 0;
DataTable dt = new DataTable();
cQuery _GraphInfo2 = new cQuery();
_GraphInfo2.Sqlstring = "SQL Statement";
DataSet ds = _GraphInfo2.SelectStatement();
dt = ds.Tables[0];
List<Data> datalist2 = new List<Data>();
foreach (DataRow dr in dt.Rows)
{
cat = dr[0].ToString();
val = Convert.ToInt32(dr[1]);
datalist2.Add(new Data(cat, val));
}
return datalist2;
}
Currently when this code runs it loads the first graph and then replaces the first graph with the second one instead of loading it into the second div tag.
Any help would be greatly appreciated.
iam using mvc, i want to connect my data to google pie chart. so i used json to get list of names and their count using the following code
public JsonResult list()
{
var result= list.GroupBy(i => i.Name).Select(i => new { word = i.Key, count = i.Count()
return Json(result.ToList(), JsonRequestBehavior.AllowGet);
}
Using the google chart API
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "list",
dataType: "json",
async: false
}).responseText;
var data = google.visualization.DataTable(jsonData);
var options = {
title: 'Certificate details',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
i want to know how to get list of key value pairs of my data into pie chart.
i have googled for long time, everybody is giving code example with php.
Thankyou.
You can parse that data client-side like this:
function drawChart () {
$.ajax({
url: "list",
dataType: "json",
success: function (jsonData) {
var data = new google.visualization.DataTable();
// assumes "word" is a string and "count" is a number
data.addColumn('string', 'word');
data.addColumn('number', 'count');
for (var i = 0; i < jsonData.length; i++) {
data.addRow([jsonData[i].word, jsonData[i].count]);
}
var options = {
title: 'Certificate details',
is3D: true
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
});
}
I created a basic handler to provide some methods to work with dinamic google charts.
First you register the data or part of it. After this, you are able to render when necessary.
Look at: http://github.com/ahlechandre/chart-handler
I was trying to implement dynamic google pie chart.But while doing so it is connecting to the database via json call but I cannot implement a piechat ,.hence i am not able to get the value for the pie chart.
My Json data which i want to is as follows:-
function getHealthReport()
{
var dataString = {auth_token: sessionStorage.auth_token,};
var mh_url = MH_HOST + '/reports/get_health_issues_report.json';
$.ajax(
{
type: "POST",
url: mh_url,
data: dataString,
dataType: "json",
success: function (data)
{/*
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart); <----- here i am getting piechart via hardcoding
function drawChart(){
var data = google.visualization.arrayToDataTable([
['Task','Hours per Day'],
['Work',11],
['Eat',2],
['Commute',2]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('outer_tableDiv'));
chart.draw(data, options);}
*/
},
error: function (data)
{
alert("fail");
}
});
}
can anyone please help.