How to push data to create pie chart - chart js - javascript

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)

Related

Chart.js - Ajax response not accept

chart.js not accept ajax post - json respose.i couldn't solve it yet.please help..
https://prnt.sc/spt4p3
https://prnt.sc/spt6j0
my json file is:
[{"DAYS":"01.05.2020","VALUES":"0"},{"DAYS":"02.05.2020","VALUES":"0"},{"DAYS":"03.05.2020","VALUES":"0"},{"DAYS":"04.05.2020","VALUES":"0"},{"DAYS":"05.05.2020","VALUES":"0"},{"DAYS":"06.05.2020","VALUES":"0"},]
javascript file is:
var days = [];
var values=[];
$.ajax({
url: 'class/report/daily_report.php',
type: 'POST',
data: {'reload': 'renew', 'type': 'rep_1'},
success: function (response) {
var jsonARR =$.parseJSON(response);
var k=0;
for ( var key in jsonARR ) {
days[k]=jsonARR[key]["DAYS"];
values[k]=parseInt(jsonARR[key]["VALUES"]);
k++;
}
}
});
var a = {
labels: days,
datasets: [{
backgroundColor: KTApp.getStateColor("danger"),
data: values
}]
};
Please remind that $.ajax() makes an asynchronous HTTP request. In you code however, you create the chart even before ans answer from that request is received.
The problem can be solved by moving the code responsible for chart creation inside the $.ajax() block as shown below.
$.ajax({
success: function(response) {
var jsonARR = $.parseJSON(response);
var k = 0;
for (var key in jsonARR) {
days[k] = jsonARR[key]["DAYS"];
values[k] = parseInt(jsonARR[key]["VALUES"]);
k++;
};
var a = {
labels: days,
datasets: [{
backgroundColor: KTApp.getStateColor("danger"),
data: values
}]
};
new Chart(...);
});

Defining function without calling it immediately without events (on click/hover...)

I have a really huge jquery function, and to make it easier to read, I'd like to know how can I put it somewhere else and call it only inside another function (to be more specific, inside an ajax call, where I have it defined right now).
The problem is that when I define the function, it runs automatically, and I don't want that. I want it to run inside the ajax call, but not define it there.
Here's a sample code of what I have:
$.ajax({
type: 'post',
url: 'api/'+$("#id").val()+"/"+$("#from").val()+"/"+$("#to").val(),
data: {},
success: function generateChart(data) {
var results = JSON.parse(data);
if (results.error == true) {
var errCode = results.code;
alert(errCode);
}
else {
var chartjsTemp = [];
var chartjsDate = [];
for (var i = 0; i < results.length; i++) {
chartjsTemp.push(results[i].probeTemp);
chartjsDate.push(results[i].dateProbe);
}
var ctx = document.getElementById('myChart').getContext('2d');
var button = $("#submitButton");
submitButton.addEventListener("click", function(){
myChart.destroy();
});
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: chartjsDate,
datasets: [{
label: 'temp',
data: chartjsTemp,
backgroundColor: "rgba(240,240,240,0.5)"
}]
}
});
}
}
});
I want to put my "generateChart" function somewhere else. If I put it "somewhere else" and do just "success: generateChart()" it won't work, and instead run when the page loads.
You should call an external function, like this:
function extFunc(data){
...
}
$.ajax({
type: 'post',
url: 'xxx',
data: {},
success: function generateChart(data) {
extFunc(data);
}
});
You should be able to save all your functions in variables without actually calling them.
Here's an example:
var myFunc = function(param1) {
console.log(param1);
}
$(function() {
myFunc('test');
myFunc('test2');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Edit:
With your code sample it's basically the same.
Just define the success function outside and then call it on success.
If you success: generateChart(data) you could also try:
success: function(data) { generateChart(data); }.
Just move the definition outside an ajax call:
function generateChart(data) {
var results = JSON.parse(data);
if (results.error == true) {
var errCode = results.code;
alert(errCode);
} else {
var chartjsTemp = [];
var chartjsDate = [];
for (var i = 0; i < results.length; i++) {
chartjsTemp.push(results[i].probeTemp);
chartjsDate.push(results[i].dateProbe);
}
var ctx = document.getElementById('myChart').getContext('2d');
var button = $("#submitButton");
submitButton.addEventListener("click", function(){
myChart.destroy();
});
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: chartjsDate,
datasets: [{
label: 'temp',
data: chartjsTemp,
backgroundColor: "rgba(240,240,240,0.5)"
}]
}
});
}
}
$.ajax({
type: 'post',
url: 'api/'+$("#id").val()+"/"+$("#from").val()+"/"+$("#to").val(),
data: {},
success: function(data) {
generateChart(data);
}
});

Pie chart crashes when no data from JSON

I am a beginner and learning web development. In my sample project I have created Pie Chart using ChartJS. I am getting data from REST Service. Everything is working fine and pie chart is getting rendered properly. The problem is when there is null data from REST then I am getting error in Chart.js.
Error:
JSON DATA FROM REST:
My sample project uses BackboneJS. I know the error is because there is no data coming from REST. How can I handle that so that m Pie Chart does not crash.
Below is the MODEL:
define(['backbone'], function(Backbone) {
var chart = Backbone.Model.extend({
urlRoot: 'SAMPLE REST URL',
defaults: function() {
return {
currMonthOccAvailVac: [],
};
},
fetch: function(data) {
var d = $.Deferred();
var self = this;
var ajaxRequest = $.ajax({
url: this.urlRoot,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(data)
});
ajaxRequest.done(function(json) {
var graphVar = {
currMonthOccAvailVac: [],
}
var yearSelected = (localStorage.getItem('date')).split("-")[0];
var monthSelected = (localStorage.getItem('date')).split("-")[1];
for (var i = 0; i < json.length; i++) {
var monthYear = json[i].columnstrDate.split("/");
var year = monthYear[0];
var month = monthYear[1];
if(month.length == 1)
if(month == (monthSelected - 1) && year == yearSelected)
{
graphVar.currMonthOccAvailVac.push(json[i].columndecOccPercentage);
graphVar.currMonthOccAvailVac.push(json[i].columndecVacantUnitsPercentage);
graphVar.currMonthOccAvailVac.push(json[i].columndecUnavailableUnitsPercentage);
}
}
self.set({
currMonthOccAvailVac: graphVar.currMonthOccAvailVac,
});
d.resolve();
});
//failure callback for ajax request.
ajaxRequest.fail(function(jqXHR, status) {
// Handle fail request
d.reject();
});
return d.promise();
}
});
// returning the model
return {
chart: chart
};
});
Place in ChartJS where actually code is breaking:
So how can I make sure even if graphvar.currMonthOccAvailVac has no value the pie chart does not crash. Kindly guide me.
EDIT
Currently in my View Model I did something like below. But I am not sure if this the right way to handle.
define(['backbone'], function(Backbone) {
var sixthSubViewModel = Backbone.View.extend({
template: _.template($('#myChart6-template').html()),
render: function() {
$(this.el).html(this.template());
var ctx = this.$el.find('#pieChart')[0];
var data = {
datasets: [{
data: this.model.attributes.currMonthOccAvailVac,
label: 'My dataset' // for legend
}],
labels: [
"Rented",
"Vacant",
"Unavailable",
]
};
// I AM CHECKING HERE THE LENGTH AND THE RNEDERING THE PIE CHART
if (this.model.attributes.currMonthOccAvailVac.length > 1)
var pieChart = new Chart(ctx, {
type: 'pie',
data: data,
otpions: {
legend: false
}
});
WHAT SHALL I PUT IN THE ELSE PART
},
initialize: function() {
this.render();
}
});
return sixthSubViewModel;
});

how to use google chart using dynamic data from json

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

How to initialize knockoutjs view model with .ajax data

The following code works great with a hardcoded array (initialData1), however I need to use jquery .ajax (initialData) to initialize the model and when I do the model shows empty:
$(function () {
function wiTemplateInit(winame, description) {
this.WIName = winame
this.WIDescription = description
}
var initialData = new Array;
var initialData1 = [
{ WIName: "WI1", WIDescription: "WIDescription1" },
{ WIName: "WI1", WIDescription: "WIDescription1" },
{ WIName: "WI1", WIDescription: "WIDescription1" },
];
console.log('gridrows:', initialData1);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{UserKey: '10'}",
url: "WIWeb.asmx/GetTemplates",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
initialData.push(new wiTemplateInit(data.d[i].WiName,data.d[i].Description));
}
//console.log('gridrows:', initialData);
console.log('gridrows:', initialData);
}
});
var viewModel = function (iData) {
this.wiTemplates = ko.observableArray(iData);
};
ko.applyBindings(new viewModel(initialData));
});
I have been trying to work from the examples on the knockoutjs website, however most all the examples show hardcoded data being passed to the view model.
make sure your "WIWeb.asmx/GetTemplates" returns json array of objects with exact structure {WIName : '',WIDescription :''}
and try using something like this
function wiTemplateInit(winame, description)
{
var self = this;
self.WIName = winame;
self.WIDescription = description;
}
function ViewModel()
{
var self = this;
self.wiTemplates = ko.observableArray();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{UserKey: '10'}",
url: "WIWeb.asmx/GetTemplates",
success: function (data)
{
var mappedTemplates = $.map(allData, function (item) { return new wiTemplateInit(item.WiName, item.Description) });
self.wiTemplates(mappedTemplates);
}
});
}
var vm = new ViewModel();
ko.applyBindings(vm);
If you show us your browser log we can say more about your problem ( Especially post and response ). I prepared you a simple example to show how you can load data with ajax , bind template , manipulate them with actions and save it.
Hope this'll help to fix your issue : http://jsfiddle.net/gurkavcu/KbrHX/
Summary :
// This is our item model
function Item(id, name) {
this.id = ko.observable(id);
this.name = ko.observable(name);
}
// Initial Data . This will send to server and echo back us again
var data = [new Item(1, 'One'),
new Item(2, 'Two'),
new Item(3, 'Three'),
new Item(4, 'Four'),
new Item(5, 'Five')]
// This is a sub model. You can encapsulate your items in this and write actions in it
var ListModel = function() {
var self = this;
this.items = ko.observableArray();
this.remove = function(data, parent) {
self.items.remove(data);
};
this.add = function() {
self.items.push(new Item(6, "Six"));
};
this.test = function(data, e) {
console.log(data);
console.log(data.name());
};
this.save = function() {
console.log(ko.mapping.toJSON(self.items));
};
}
// Here our viewModel only contains an empty listModel
function ViewModel() {
this.listModel = new ListModel();
};
var viewModel = new ViewModel();
$(function() {
$.post("/echo/json/", {
// Data send to server and echo back
json: $.toJSON(ko.mapping.toJS(data))
}, function(data) {
// Used mapping plugin to bind server result into listModel
// I suspect that your server result may contain JSON string then
// just change your code into this
// viewModel.listModel.items = ko.mapping.fromJSON(data);
viewModel.listModel.items = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
});
})

Categories

Resources