$(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 [ [] ]
Related
I have data from SQL in json code file (checked in Fiddler)
{"d":[{"__type":"Dashboards.Employee","name":"Test
Hen","turnover":"1500000,0000","color":"#231F20"},{"__type":"Dashboards.Employee","name":"Test
Bai","turnover":"130000,0000","color":"#FFC200"}]}
but i dont know, how to push them correctly in order to create pie chart
my ajax/javascript is here:
$.ajax({
url: 'HelloService.asmx/GetEmployeeDetail',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ month: number }),
dataType: 'json',
method: 'post',
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
var aData = response.d;
var arr = [];
//var ctx = document.getElementById('pele').getContext('2d');
$.each(aData, function (inx, val) {
var obj = {};
obj.label = val.name;
obj.value = val.turnover;
obj.color = val.color;
arr.push(obj);
});
var ctx = $("#pele").get(0).getContext("2d");
var myPieChart = new Chart(ctx).Pie(arr);}
function OnErrorCall_(response) {
console.log(error);
}
});
});
Am I missing something?
If i use static values (value, label, color) pie chart works without problem.
Thank you
I created the following FiddleJS for you: https://jsfiddle.net/cukyrh5h/1/
You need to replace the URL of the Ajax call with yours of course. You had some wrong syntax (too much braches in the end of your Snippet) and the API you were using was not working with ChartJS 2.4 anymore.
The code looks like the following:
$.ajax({
url:"/echo/json/",
data:data,
type:"POST",
success:OnSuccess_
});
function OnSuccess_(response) {
var aData = response.d;
var data = {
labels: [],
datasets: [{
data: [],
backgroundColor: []
}]
};
$.each(aData, function (inx, val) {
data.labels.push(val.name);
data.datasets[0].data.push(val.turnover);
data.datasets[0].backgroundColor.push(val.color);
});
var ctx = $("#pele").get(0).getContext("2d");
var myPieChart = new Chart(ctx, {
type: 'pie',
data: data
});
}
function OnErrorCall_(response) {
console.log(error);
}
Ok, i found problem, why i cant see my Chart. Maybe it will be useful for another members. Data in Database (turnover was daclared as money, i changed it to int .... and it works)
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);
I am in the process of deploying a set of Google Charts into SharePoint 2013. I am running into this issue where it isn't loading my data. I have tested it out in just a standard application page and it works perfectly. I will show my code below:
<script type="text/javascript">
//approver chart
var chartDataApprover; // globarlvariable to hold chart data
google.load("visualization", "1", { packages: ["corechart"] });
$(document).ready(function () {
$.ajax({
url: "Chart_Application_Page.aspx/GetChartDataApprover",
data: "",
dataType: "json",
type: "POST",
contentType: "application/json; chartset=utf-8",
success: function (data) {
chartDataApprover = data.d;
},
error: function () {
alert("Error loading data! Please try again.");
}
}).done(function () {
//after data is loaded
google.setOnLoadCallback(drawChartApprover);
drawChartApprover();
});
});
</script>
//approver function
function drawChartApprover() {
var data = google.visualization.arrayToDataTable(chartDataApprover);
//groups chart data by name
var resultApprover = google.visualization.data.group(data, [0], [{ 'column': 1, 'aggregation': google.visualization.data.sum, 'type': 'number' }]);
var options = {
title: "Approver Spending",
pointSize: 5
};
var pieChartApprover = new google.visualization.PieChart(document.getElementById('chart_div_approver'));
pieChartApprover.draw(resultApprover, options);
}
I believe my error is coming on the line where I am setting the content type. I am deploying this into SharePoint 2013 via an Application Page... with code behind in C#.
Can anyone help me out with this issue?
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.