Django/Javascript - Data won't display in chart - javascript

Chart shows correctly like so:
But this one does not display the bar:
This line is displayed as warning/error where default2 is:
Unresolved variable default2
I have commented down below for you to see and added a picture where this error displays:
How do I make the chart above appear with a bar like the other one?
Been doing these for days and hours and looked for answers here with no luck. Hopefully you can see where I went wrong.
Still a newbie so I appreciate all your help, folks!
chart.js
var endpoint = '/api/chart/data/';
var defaultData = [];
var labels = [];
var defaultData2 = [];
var labels2 = [];
$.ajax({
method: "GET",
url: endpoint,
success: function (data) {
labels = data.labels;
defaultData = data.default;
setChart()
},
error: function (error_data) {
console.log("error");
console.log(error_data)
}
});
$.ajax({
method: "GET",
url: endpoint,
success: function (data) {
labels2 = data.labels2;
defaultData2 = data.default2; # default2 displays as incorrect/warning???
setChart2()
},
error: function (error_data) {
console.log("error");
console.log(error_data)
}
});
function setChart2(){
var ctx = document.getElementById("myChart5");
var myChart5 = new Chart(ctx, {
type: 'bar',
data: {
labels2: labels2,
datasets: [{
label: 'Total',
data: defaultData2,
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,
callback: function(value) {if (value % 1 === 0) {return value;}}
}
}]
}
}
});}
function setChart(){
var ctx = document.getElementById("myChart1");
var myChart1 = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Total',
data: defaultData,
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,
callback: function(value) {if (value % 1 === 0) {return value;}}
}
}]
}
}
});
views.py
from django.shortcuts import render
from django.views.generic import View
from django.http import JsonResponse
from django.contrib.auth import get_user_model
from SiO.member.models import Member
from SiO.CoAdmin.models import Administrator
from rest_framework.views import APIView
from rest_framework.response import Response
import datetime
User = get_user_model()
class ChartView(View):
def get(self, request, *args, **kwargs):
return render(request, 'chart/ChartView.html', {})
class ChartViewMonth(View):
def get(self, request, *args, **kwargs):
return render(request, 'chart/ChartView/month.html', {})
class ChartData(APIView):
def get(self, request, format=None):
today = datetime.date.today()
qs_count = Administrator.objects.filter(association=self.request.user.association).count()
qs_count1 = Member.objects.filter(association=self.request.user.association).count()
qs_count2 = Member.objects.filter(reg_date__year=today.year,
reg_date__month=today.month).filter(
association=self.request.user.association).count()
labels2 = ["January"]
default_items2 = [qs_count2, ]
labels = ["Board", "Members"]
default_items = [qs_count, qs_count1]
data = {
"labels": labels,
"default": default_items,
"labels2": labels2,
"default2": default_items2,
}
return Response(data)
urls.py
from django.conf.urls import url
from . import views
from django.contrib.auth import get_user_model
User = get_user_model()
urlpatterns = [
url(r'^ChartView/$', views.ChartView.as_view(), name='ChartView'),
url(r'^ChartView/month$', views.ChartViewMonth.as_view(), name='ChartView/month'),
url(r'^api/chart/data/$', views.ChartData.as_view()),
]

Related

How to pass a state variable into a function in React?

It is widely known that it is possible to declare state variables in react js files and have those state variables appear in the render() function.
However, I am faced with an application in which I have to get the value of certain state variables and pass their values into an object called "data" (see code below) that feeds into a component that makes tables (like bar charts, graphs, etc.). I am attempting to use a GET request from HTTP to get the values of the state variables, which works fine (I hope), but the state variables simply won't go into the data array data: []. I would appreciate some help. Further code is down below.
constructor(props) {
super(props);
this.state = {
teacher_name: '',
confusion: 0,
surprised: 0,
happy: 0,
sad: 0,
}
componentDidMount() {
axios.get('http://localhost:8000/api/school/frames/' + localStorage.getItem('first_name') + '_' + localStorage.getItem('last_name'))
.then(response =>
{
this.setState({teacher_name: response.teacher_name, confusion: response.confusion, surprised: response.surprised, happy: 100, sad: response.sad})
console.log(response)
})
.catch(error => {
console.log(error)
})
}
data = {
labels: ["Happy", "Sad", "Surprised", "Confused"],
datasets: [this.state.happy(), {
label: '# of Votes',
data: [**ATTEMPTING TO PUT STATE VARIABLES HERE**],
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,
fill: false
}]
};
data =[{this.state.yourState}]
or
var myData = this.state.yourState
data = {
labels: ["Happy", "Sad", "Surprised", "Confused"],
datasets: [this.state.happy(), {
label: '# of Votes',
data: [{myData}],
...
}
or
var myData = this.state.yourState
data = {
labels: ["Happy", "Sad", "Surprised", "Confused"],
datasets: [this.state.happy(), {
label: '# of Votes',
data: [myData],
...
}

Chart.js how to inser values from json

I have an issue inserting in Chart.js only two values(timestamp and cpu telemetry) from external JSON(which is located remotely on VPS). In Console all data loaded correctly, my code is:
var theCpuUrl = "http://" + address + "/api/metric/cpu";
var xmlhttp = new XMLHttpRequest();
var ctx = document.getElementById('cpuchart').getContext('2d');
var cpuchart = new Chart(ctx, {
type: 'bar',
data: {
labels: '......',
datasets: [{
label: 'cpu',
data: [80, 70, 80, 20, 10, 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: false
}
}]
}
}
}
});
httpGetAsync(theCpuUrl, function(data, status) {
var myData = JSON.parse(data);
for (var i = 0; i < myData[0].length; i++) {
let time = myData[0][i].timestamp;
let value = myData[0][i].cpu;
}
});
xmlhttp.open("GET", theCpuUrl, true);
console.log(xmlhttp.readyState);
This code is also connected to global.js with next code:
var address = "192.168.13.60:12345"
function httpGetAsync(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlHttp.send(null);
}
Please somebody can you explain me how do I draw data on Y and X axis.
Thank you very much.
Welcome to Stackoverflow. The issue is coming because you have initialised the chart first new Chart and you're getting the updated values asynchronously. You can solve this problem by initialising chart once you have received the data.
e.g.
httpGetAsync(theCpuUrl, function(data, status) {
var myData = JSON.parse(data);
// storing time and values
let time=[], value=[];
for (var i = 0; i < myData[0].length; i++) {
time.push(myData[0][i].timestamp);
value.push(myData[0][i].cpu);
}
// now you have data in time and value array ready
--> here call the "new Chart" which you're calling above. <--
});

How to get the angularjs scope variable data to the chartjs data

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.

Chart.js passing value data dynamic

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

Need help Chart.js in asp.net mvc

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);
});
});

Categories

Resources