I am trying to pass the value from the scope variable of the angularjs controller to the chartjs data.
this is my master.controller.js - The chartjs is inside the master.controller.js file:
/**
* Master Controller
*/
// Global variables for chart.js
var totalTripsCompleted = '';
var TruckTripsFortheDay = [];
var totalTrucks = [];
var totalNumberofTripsCompleted = '';
var numberoftrucks = [];
angular.module('App')
.controller('MasterCtrl', ['$scope','$http','StorageService','PagingUtil','$state','$rootScope', function ($scope, $http, StorageService, PagingUtil, $state, $rootScope) {
$scope.client = false;
$scope.stateName = '';
$scope.loggedIn = false;
$scope.landingPage = "shipments"
var samplearrayvar = [];
$scope.init = function(){
}
// $scope.dueRenewal = 0;
// $scope.dueService = 0;
// $scope.dueSoonRenewal = 0;
// $scope.dueSoonService = 0;
$scope.user = {};
$scope.typeCount = [];
$scope.getDueRenewal = function(){
$http.get("/api/renewalReminders?status=due").success(function(response,status,headers){
$scope.dueRenewal = headers('X-Total-Count');
});
}
$scope.getDueService = function(){
$http.get("/api/serviceReminders?status=due").success(function(response,status,headers){
$scope.dueService = headers('X-Total-Count');
});
}
$scope.getDueSoonRenewal = function(){
$http.get("/api/renewalReminders?status=dueSoon").success(function(response,status,headers){
$scope.dueSoonRenewal = headers('X-Total-Count');
});
}
$scope.getDueSoonService = function(){
$http.get("/api/serviceReminders?status=dueSoon").success(function(response,status,headers){
$scope.dueSoonService = headers('X-Total-Count');
});
}
$scope.checkIfLoggedIn = function(){
$scope.user = StorageService.get("user");
$rootScope.user = false;
$http.get("/api/account").success(function(response){
$scope.loggedIn = true;
if($scope.user == null){
$scope.user = response;
$rootScope.user = response;
StorageService.save("user",$scope.user);
}
if($scope.user.login == response.login){
if($state.current.name=="login"){
$state.go($scope.landingPage);
}
}
}).error(function(){
$scope.loggedIn=false;
$scope.user = false;
if($state.current.name!="login" && $state.current.name!=$scope.landingPage){
console.log("last state");
$rootScope.attemptedState = $state.current.name;
$rootScope.attemptedStateParams = $state.params;
}
StorageService.clearAll();
$state.go("login");
});
}
$scope.redirectFromLastAttempt = function(){
if($rootScope.attemptedState){
var go = $rootScope.attemptedState;
$rootScope.attempatedState = false;
$state.go(go,$rootScope.attemptedStateParams);
return;
}
}
$scope.checkIfLoggedIn();
$scope.request = {};
$scope.login = function(){
$http.post("/api/authenticate",$scope.request)
.success(function(response){
$scope.checkIfLoggedIn();
});
}
$scope.changePassword = function(){
$http.post("/api/account/change_password",$scope.request)
.success(function(response){
$state.go($scope.landingPage);
}).error(function(response){
console.log(response);
alert("Cannot change password. invalid old password");
});
}
$scope.logout = function(){
StorageService.clearAll('user',$scope.user);
$http.delete("/api/authenticate?username="+$scope.request.username+"&password="+$scope.request.username)
.success(function(response){
$scope.checkIfLoggedIn();
}).error(function(response){
$scope.checkIfLoggedIn();
});
}
$rootScope.getDestinations = function(customerId,list){
$http.get("/api/destinations?customerId="+customerId).success(function(response){
list = response;
});
}
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
$scope.stateName = toState.name;
$scope.checkIfLoggedIn();
});
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
$scope.stateName = toState.name;
console.log($scope.stateName);
if($scope.stateName=='index'){
$scope.getDueRenewal();
$scope.getDueService();
$scope.getDueSoonRenewal();
$scope.getDueSoonService();
}
if(fromState.name){
$rootScope.fromState = fromState.name;
$rootScope.fromParams = fromParams;
}
});
$rootScope.showError = function(message,title){
$rootScope.errorMessage = message;
$rootScope.errorMessageTitle = null;
if(title){
$rootScope.errorMessageTitle = title;
}
$("#error-modal").modal('show');
};
$rootScope.$on('loading:progress', function (){
// show loading gif
$("#loading-modal").modal({keyboard:false,show:true,backdrop:'static'});
});
$rootScope.$on('loading:finish', function (){
// hide loading gif
// setTimeout(function(){
$("#loading-modal").modal("hide");
// },5000);
});
$rootScope.hasAccess = function(rolenames){
if($scope.user){
if($scope.user.roles){
if($scope.user.roles.indexOf('ROLE_ADMIN')>-1){
return true;
}
}else{
return false;
}
}else{
return false;
}
for(var i in rolenames){
if($scope.user.roles.indexOf(rolenames[i])>-1){
return true;
}
}
return false;
}
//Daily Truck Utilization-------------------------------------------------------------------------------
$scope.getTrucksDispatched = function() {
$scope.trucksample = [];
var currentDate = new Date();
var day = currentDate.getDate();
var month = currentDate.getMonth();
var year = currentDate.getFullYear();
$scope.truckdispatcheddate = "(" + month + "-" + day + "-" + year + ")";
$http.get("/api/shipmentstatusanddispatched").success(function(response){
totalTripsCompleted = response;
console.log(response);
});
}
$scope.getTotalNumberofTrucks = function() {
$http.get("/api/vehicleTrucks").success(function(response) {
$scope.totalNumberofTrucks = response[0];
console.log(response);
});
}
//Number of trips running-------------------------------------------------------------------------------
var samplearray = [];
$scope.getVehicleTypeCount = function(){
$http.get("/api/vehicleTrucks").success(function(response){
// for (var i = 0; i < response.length; i++) {
// var count = 0;
// var key = response[i].commodityType;
// $scope.count = {};
// for (var j = 0; j < response.length; j++) {
// if(response[j].commodityType == key){
// count++;
// }
// }
// $scope.count[key] = count;
// $scope.typeCount.push($scope.count);
// samplearray.push(response[i].commodityType);
// }
console.log(response);
});
}
$scope.numberOfTrips = function() {
$scope.getTotalCompletedTrips = '';
$http.get("/api/shipmentcountstatuscompleted").success(function(response) {
$scope.getTotalCompletedTrips = response;
totalNumberofTripsCompleted = response;
console.log($scope.getTotalCompletedTrips);
});
}
//Number or % of Dry, Chilled, Reefer trips for the day--------------------------------------------
// $scope.getCommodityTypeVehicleQuantity = function() {
//
// //
// }
//% Truck break down ( repairs and maint) and average number of days down--------------------------
//POD status -dispatched, delivered, completed (running) / unbilled--------------------------------
$scope.tripStatus = function() {
var dispatched = '';
var delivered = '';
var completed = '';
var totaltrips = '';
$http.get("/api/shipmentcountstatusdispatched").success(function(response) {
dispatched = response;
});
$http.get("/api/shipmentcountstatusdelivered").success(function(response) {
delivered = response;
});
$http.get("/api/shipmentcountstatuscompleted").success(function(response) {
completed = response;
});
$http.get("/api/shipmentTotaltrips").success(function(response) {
totaltrips = response;
});
$scope.completionrate = completed / totaltrips;
}
//Average Diesel consumption per client(?) against target------------------------------------------
$scope.tripStatus();
$scope.numberOfTrips();
$scope.getTotalNumberofTrucks();
$scope.getTrucksDispatched();
}]);
var trucksperdepotid = document.getElementById('trucksperdepot').getContext('2d');
var trucksperdepotChart = new Chart(trucksperdepotid, {
type: 'bar',
data: {
labels: ['Depot 1', 'Depot 2', 'Depot 3', 'Depot 4', 'Depot 5'],
datasets: [{
label: 'Number of Trucks per Depot',
data: [
90,
80,
70,
60,
50
],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
var tripscompletedid = document.getElementById('tripscompleted').getContext('2d');
var tripscompletedChart = new Chart(tripscompletedid, {
type: 'bar',
data: {
labels: ['Number of Trips Completed'],
datasets: [{
label: 'Number of trips completed',
data: [
totalNumberofTripsCompleted
],
backgroundColor: [
'rgba(255, 99, 132, 0.2)'
// 'rgba(255, 99, 132, 0.2)',
// 'rgba(54, 162, 235, 0.2)',
// 'rgba(255, 206, 86, 0.2)',
// 'rgba(75, 192, 192, 0.2)',
// 'rgba(153, 102, 255, 0.2)',
// 'rgba(255, 159, 64, 0.2)',
// 'rgba(153, 102, 255, 0.2)',
// 'rgba(153, 102, 255, 0.2)',
// 'rgba(153, 102, 255, 0.2)',
// 'rgba(153, 102, 255, 0.2)',
// 'rgba(153, 102, 255, 0.2)',
// 'rgba(153, 102, 255, 0.2)',
// 'rgba(153, 102, 255, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)'
// 'rgba(255,99,132,1)',
// 'rgba(54, 162, 235, 1)',
// 'rgba(255, 206, 86, 1)',
// 'rgba(75, 192, 192, 1)',
// 'rgba(153, 102, 255, 1)',
// 'rgba(255, 159, 64, 1)',
// 'rgba(153, 102, 255, 1)',
// 'rgba(153, 102, 255, 1)',
// 'rgba(153, 102, 255, 1)',
// 'rgba(153, 102, 255, 1)',
// 'rgba(153, 102, 255, 1)',
// 'rgba(153, 102, 255, 1)',
// 'rgba(153, 102, 255, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
var commoditytypeid = document.getElementById('commoditytype').getContext('2d');
//commoditytypeid.height=100;
var commoditytypeChart = new Chart(commoditytypeid, {
type: 'pie',
data: {
datasets: [{
data: [
20,
30,
40,
50
],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
labels: [
'Dry',
'Chilled',
'Frozen',
'Wet'
]
},
options: {
}
});
var commoditytypetodayid = document.getElementById('commoditytypetoday').getContext('2d');
//commoditytypeid.height=100;
var commoditytypeChart = new Chart(commoditytypetodayid, {
type: 'pie',
data: {
datasets: [{
data: [
20,
30,
40,
50
],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
labels: [
'Dry',
'Chilled',
'Frozen',
'Wet'
]
},
options: {
}
});
var commoditytypeyesterdayid = document.getElementById('commoditytypeyesterday').getContext('2d');
//commoditytypeid.height=100;
var commoditytypeChart = new Chart(commoditytypeyesterdayid, {
type: 'pie',
data: {
datasets: [{
data: [
20,
30,
40,
50
],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
labels: [
'Dry',
'Chilled',
'Frozen',
'Wet'
]
},
options: {
}
});
var commoditytypethisweekid = document.getElementById('commoditytypethisweek').getContext('2d');
//commoditytypeid.height=100;
var commoditytypeChart = new Chart(commoditytypethisweekid, {
type: 'pie',
data: {
datasets: [{
data: [
20,
30,
40,
50
],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
labels: [
'Dry',
'Chilled',
'Frozen',
'Wet'
]
},
options: {
}
});
var commoditytypethismonthid = document.getElementById('commoditytypethismonth').getContext('2d');
//commoditytypeid.height=100;
var commoditytypeChart = new Chart(commoditytypethismonthid, {
type: 'pie',
data: {
datasets: [{
data: [
20,
30,
40,
50
],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
labels: [
'Dry',
'Chilled',
'Frozen',
'Wet'
]
},
options: {
}
});
var truckdownid = document.getElementById("truckdown").getContext("2d");
var truckdownChart = new Chart(truckdownid, {
type: 'bar',
data: {
labels: ['Truck Down'],
datasets: [{
label: 'Vehicles with On-Service Status',
backgroundColor: "rgba(255, 99, 132, 0.2)",
borderColor: 'rgba(255,99,132,1)',
data: [80]
}, {
label: 'Number of fleet',
backgroundColor: "rgba(54, 162, 235, 0.2)",
borderColor: 'rgba(54, 162, 235, 1)',
data: [90]
}]
},
options: {
legend: {
display: true,
labels: {
fontColor: "#000080",
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
var truckdownaverageid = document.getElementById("truckdownaverage").getContext("2d");
var truckdownaverageChart = new Chart(truckdownaverageid, {
type: 'bar',
data: {
labels: ['Truck Down Average'],
datasets: [{
label: 'Vehicles with On-Service Status',
backgroundColor: "rgba(255, 99, 132, 0.2)",
borderColor: 'rgba(255,99,132,1)',
data: [80]
}, {
label: 'Number of fleet',
backgroundColor: "rgba(54, 162, 235, 0.2)",
borderColor: 'rgba(54, 162, 235, 1)',
data: [90]
}]
},
options: {
legend: {
display: true,
labels: {
fontColor: "#000080",
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
var tripstatusforthemonthid = document.getElementById('tripstatusforthemonth').getContext('2d');
//commoditytypeid.height=100;
var tripstatusforthemonthChart = new Chart(tripstatusforthemonthid, {
type: 'pie',
data: {
datasets: [{
data: [
20,
30,
40,
50
],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
labels: [
'Dry',
'Chilled',
'Frozen',
'Wet'
]
},
options: {
}
});
var tripscreatedid = document.getElementById('tripscreated').getContext('2d');
var tripscreatedChart = new Chart(tripscreatedid, {
type: 'doughnut',
data: {
datasets: [{
data: [
20,
30,
40,
50
],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
labels: [
'Dry',
'Chilled',
'Frozen',
'Wet'
]
},
options: {
}
});
var averagedieselconsumptionid = document.getElementById('averagedieselconsumption').getContext('2d');
var averagedieselconsumptionChart = new Chart(averagedieselconsumptionid, {
type: 'doughnut',
data: {
datasets: [{
data: [
20,
30,
40,
50
],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
labels: [
'Dry',
'Chilled',
'Frozen',
'Wet'
]
},
options: {
}
});
I am trying to get the value of the $scope.totalNumberofTrucks to the data of the chartjs. But when i try to pass the value of that scope to a global variable, the global variable I declared in the chartjs data is still empty / null.
I am want to use data and level dynamic by ajax, so i am using as below but not working.
My ajax return data in json_encode of php.
My code is:
success: function (result) {
result = JSON.parse(result);
var labels = result['labels'];
var data = result['data'];
//console.log(data);
var ctx = document.getElementById("chartbtc");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [labels],
datasets: [{
label: 'Market Price (USD)',
data: [data],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
}
}
});
}
But chart is not generating:
Ajax result is:
{"labels":"13-Nov-2017, 14-Nov-2017, 15-Nov-2017, 16-Nov-2017, 17-Nov-2017, 18-Nov-2017, 19-Nov-2017, 20-Nov-2017, 21-Nov-2017, 22-Nov-2017, 23-Nov-2017, 24-Nov-2017, 25-Nov-2017, 26-Nov-2017, 27-Nov-2017, 28-Nov-2017, 29-Nov-2017, 30-Nov-2017, 01-Dec-2017, 02-Dec-2017, 03-Dec-2017, 04-Dec-2017, 05-Dec-2017, 06-Dec-2017, 07-Dec-2017, 08-Dec-2017, 09-Dec-2017, 10-Dec-2017, 11-Dec-2017, 12-Dec-2017","data":"6550.22, 6635.41, 7301.42, 7815.03, 7786.88, 7817.14, 8007.65, 8255.59, 8059.8, 8268.03, 8148.94, 8250.97, 8707.4, 9284.14, 9718.29, 9952.5, 9879.32, 10147.37, 10883.91, 11071.36, 11332.62, 11584.82, 11878.43, 13540.98, 16501.97, 16007.43, 15142.83, 14869.8, 16762.11, 17276.39"}
Since you have provided your ajax result, this will not work with the chart generation. In your case result["labels"] is a string and you are just making a list with 1 element which is the whole string(which is not valid for the labels property and will not work). What you should do is split the string, format it correctly and then supply it as a list to the labels property. Easiest way would be to use the split() function, and in your case you could split by ", ". Although I would recommend to implement a better response if its possible (have it something like so: {"labels": ["13-Nov-2017", "14-Nov-2017", ...]}).
Hope this helps!
For the first time you can fill the chart with your own value, but when it is coming for dynamically appending data then you should remove the canvas element and regenerate it. So that your data will get appended dynamically on chart.
You can try something like this.
<canvas id="chartbtc" class="canvasChart"></canvas>
<script>
dynamicDataAppendOnChart(labels, data); // On page loading you will be having your own data so you can pass them, or if you want that to be happen with ajax when page loading itself you can trigger the click event.
$('#btnClick').trigger('click');
// You will be calling the function with click event...
$('#btnClick').on('click', function () {
var data = '', labels = '';
$.ajax({
url: url,
type: "POST",
data: data,
async: isAsync,
success: function (result) {
result = JSON.parse(result);
labels = result['labels'];
data = result['data'];
}
});
dynamicDataAppendOnChart(labels, data); // Now you can call the function by passing labels and data
});
function dynamicDataAppendOnChart() {
$('#chartbtc').remove();
$('#appendTheCanvasElement').append('<canvas id="chartbtc" class="canvasChart"><canvas>'); // This would create new canvas element every time and removes the older one.
var ctx = document.getElementById("chartbtc");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [labels],
datasets: [{
label: 'Market Price (USD)',
data: [data],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
}
}
});
}
</script>
Try This.
Declare label and data as
var labels = result['labels'].split(","); // Return Array of Strings Of labels
var data = JSON.parse("[" + result['data'] + "]");// return array of data
Chage
labels: [labels],
data: [data],
to
labels: labels,
data: data,
Because it already in array
A few days can make a graph, we need your guidance.
Arrow displays the objects, but on the chart nothing is displayed. The search was not successful.
My models:
public class Voting
{
public int Id { get; set; }
public string Name { get; set; }
public int Voice { get; set; }
public DateTime DateVote { get; set; }
public string IpAdress { get; set; }
}
My controller:
[HttpGet]
public JsonResult GetVotings()
{
List<Voting> votings = db.Votings.ToList();
return Json(votings, JsonRequestBehavior.AllowGet);
}
Probably the main problem in the script calling the data did. While it is possible the controller is not properly configured to output data, will be very glad of your help.
My View:
<canvas id="ChartVote" width="300" height="200"></canvas>
<script type="text/javascript" charset="utf-8">
$(function () {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: 'json',
url: '/Chart/GetVotings',
}).done(function (votings) {
console.log(votings);
$.each(votings, function (index, data) {
myChart.labels.push(data.Name);
myChart.datasets[0].data.push(data.Voice);
});
});
});
var ctx = document.getElementById("ChartVote");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: '# of Votes',
data: [],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
Your code has few problems ! First of all, inside your $.each you are trying to access labels property of myChart. But you did not define what myChart variable is. So you are going to get an undefined error!
Another thing to think about is, your ajax call is asynchronous. It may take a long time to get the data. So whenever you get the data, you need to execute the code to render the chart with that data. I suggest you move that code to a method and call that method in your ajax call's success/done event.
This should work.
function renderChart(labels, voice) {
var ctx = document.getElementById("ChartVote");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: '# of Votes', data: voice,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: { beginAtZero: true }
}]
}
}
});
}
Now in your ajax call's done event, you can pass the label array and data array to your RenderChart method.
$(function(){
$.ajax({
type: "GET",
url: '#Url.Action("GetVotings","Chart")',
}).done(function (votings) {
var labelsArray = [];
var dataArray = [];
$.each(votings, function (index, data) {
labelsArray.push(data.Name);
dataArray.push(data.Voice);
});
renderChart(labelsArray, dataArray);
});
});