dynamically update Chart.js draw line chart dataset data - javascript

How do i pass back the value after retrieved into the dataset data? Currently it is return empty in value. I know the var durationChartData return in empty due to the intialization of array are empty, how could i update it and display the right value after i got the value from ajax?
var durationChartData = [];
var lineChartData = {
labels: ["Jan","Feb", "Mar","Apr","May","Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
datasets: [
{
label: "My Second dataset",
fillColor: "rgba(124,181,236,0.4)",
strokeColor: "rgba(124,181,236,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [durationChartData[0],durationChartData[1],durationChartData[2],durationChartData[3],durationChartData[4],durationChartData[5],durationChartData[6],durationChartData[7],durationChartData[8],durationChartData[9],durationChartData[10],durationChartData[11]]
}
]
};
window.onload = function(){
$.ajax({
url: '/rest/analytical/home/viewed/line',
type: 'GET',
dataType: 'json',
success: function (data) {
dataLength = (data + '').length;
for(var i=0; i<dataLength; i++){
durationChartData[i] = data.ret[i].all;
}
},
error: function (data) {
console.log('duration Chart Data: ' + data);
}
});
var linegraph = document.getElementById("linegraph");
var bargraph = document.getElementById("bargraph");
if(linegraph !== null){
var ctx = linegraph.getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %> min",
responsive: true
});
};

Change the part of the dataset that you receive from the ajax response, then call the chart's update() function. This is done with the 2 additional lines at the end of the $.ajax success function.
$.ajax({
url: '/rest/analytical/home/viewed/line',
type: 'GET',
dataType: 'json',
success: function (data) {
dataLength = (data + '').length;
for(var i=0; i<dataLength; i++){
durationChartData[i] = data.ret[i].all;
}
window.myLine.data.datasets[0].data = durationChartData;
// 1.x compatible answer (comment out line above):
// for(i=0; i <durationChartData.length; i++) {
// window.myLine.datasets[0].points[i].value = durationChartData[i];
// }
window.myLine.update();
},
error: function (data) {
console.log('duration Chart Data: ' + data);
}
});

Related

How to modularize large js file with JQuery functions?

I currently have one js file that serves all the html scripts, that is starting to become tedious.
It looks like this:
// Using .html in jQuery big NO NO: https://medium.com/#jenlindner22/the-risk-of-innerhtml-3981253fe217, switched to .text
// Chart Variables
var teamProgressChart
// Get initial value from filters in /table
var seasonSelection = $('#seasonToggle').children(":first").val()
var typeSelection = $('#homeAwayToggle').children(":first").val()
var MatchweekSelection = $('#homeAwayToggle').children(":first").val()
// var leagueTableUpdateTimeStamp = 0
/**
* Team progress chart update in /table
*/
$(".clickable-row").click(function() {
const teamVal = $(this).attr('value')
$.ajax({
type: 'POST',
url: '/table/team?' + $.param({ teamId: teamVal }),
success: (res) => {
var result = res[0]
var points = result.pointsAll
var position = result.positionAll
var labels = result.gameweeks
console.log(points)
console.log(position)
console.log(labels)
if (teamProgressChart) {
teamProgressChart.data.labels = labels
teamProgressChart.data.datasets[0].data = points
teamProgressChart.data.datasets[1].data = position
teamProgressChart.update()
} else {
var ctx = document.getElementById('team-progress-graph').getContext('2d');
Chart.defaults.global.defaultFontSize = 24;
teamProgressChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [
{
label: "Points",
fillColor: "rgba(0,0,0,0)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(200,122,20,1)",
borderColor: "rgba(43, 87, 29, 0.9)",
fill: false,
data: points,
yAxisID: 'points'
},
{
label: "Position",
fillColor: "rgba(172, 26, 26, 0.9)",
strokeColor: "rgba(172, 26, 26, 0.9)",
pointColor: "rgba(172, 26, 26, 0.9)",
borderColor: "rgba(14, 86, 168, 0.9)",
fill: false,
data: position,
yAxisID: 'position'
},
],
},
options: {
scales: {
xAxes: [
{
ticks: {
fontSize: 24,
autoSkip: false,
beginAtZero: true
}
}
],
yAxes: [
{
id: 'points',
min: 0,
position: 'left',
ticks: {
fontSize: 24,
beginAtZero: true
}
},
{
id: 'position',
suggestedMin : 0,
suggestedMax : 20,
position: 'right',
ticks: {
fontSize: 24
}
},
]
},
display: false,
},
})
}
}
})
})
/**
* Button to updata data in /table
*/
$('#updateDataButton').bind('click', function(event){
console.log(event.timeStamp)
$.ajax({
type: 'POST',
url: '/table',
success: () => {
console.log('success')
window.location = "/";
}
})
});
/**
* Click eventlistner for home-page player stats
*/
const homeTable = document.querySelectorAll(".stats-item");
homeTable.forEach(element => {
element.addEventListener('click', homeTableToggle)
})
function homeTableToggle(event){
var queryVal = event.target.value
console.log(queryVal)
if (queryVal == 1){
$.ajax({
type: 'POST',
url: '/?' + $.param({ statsType: queryVal}),
success: (newVals) => {
$('#stats-placehld').text("AvgPlayTime")
$('#stats-placehld1').text("AvgPasses")
console.log($('#stats-placehld1').textContent)
$('#playerStatsAvg').empty();
for(let i = 0; i < 50; i++) {
let filteredTr = newVals[i]
let newHtml = `<tr>
<td>${filteredTr.name}</td>
<td>${filteredTr.teamName}</td>
<td>${filteredTr.position}</td>
<td>${filteredTr.averagePlaytime}</td>
<td>${filteredTr.averagePasses}</td>
</tr>`
$('#playerStatsAvg').append(newHtml)
}
}
})
} else if (queryVal == 2){
$.ajax({
type: 'POST',
url: '/?' + $.param({ statsType: queryVal}),
success: (newVals) => {
$('#stats-placehld').text("AvgShots")
$('#stats-placehld1').text("AvgOnTarget")
$('#playerStatsAvg').empty();
for(let i = 0; i < 50; i++) {
let filteredTr = newVals[i]
let newHtml = `<tr>
<td>${filteredTr.name}</td>
<td>${filteredTr.teamName}</td>
<td>${filteredTr.position}</td>
<td>${filteredTr.averageShotsPerGame}</td>
<td>${filteredTr.averageShotsOnTarget}</td>
</tr>`
$('#playerStatsAvg').append(newHtml)
}
}
})
}
}
//Click eventlistner for all table-filters
const selection = document.querySelectorAll(".dropdown-item");
selection.forEach(element => {
element.addEventListener('click', pickSelection)
})
function pickSelection(event) {
let text = ""
switch(event.target.parentElement.id){
case 'seasonToggle':
text = event.target.textContent
$('#seasonvalue').text(text)
seasonSelection = event.target.value
break
case 'homeAwayToggle':
text = event.target.textContent
$('#typevalue').text(text)
typeSelection = event.target.value
break
case 'matchWeekToggle':
text = event.target.textContent
$('#matchDropDownMenyButton').text(text)
MatchweekSelection = event.target.value
break
}
//Get request for
$.ajax({
type: 'POST',
url: '/table?' + $.param({ seasonVal: seasonSelection,
typeVal: typeSelection,
matchWeekVal: MatchweekSelection}),
success: (filteredSeasonValues) => {
$('#league-table-rows').empty();
for(let i = 0; i < 20; i++) {
let filteredTr = filteredSeasonValues[i]
let newHtml = `<tr>
<td>${i+1}</td>
<td><img src='badges/${filteredTr.team_shortName}.png' />
${filteredTr.team_shortName}</td>
<td>${filteredTr.played}</td>
<td>${filteredTr.won}</td>
<td>${filteredTr.drawn}</td>
<td>${filteredTr.lost}</td>
<td>${filteredTr.goalsFor}</td>
<td>${filteredTr.goalsAgainst}</td>
<td>${filteredTr.goalsDifference}</td>
<td>${filteredTr.points}</td>
</tr>`
$('#league-table-rows').append(newHtml)
}
}
})
}
How would one go about splitting it into multiple files, let's say page specific and importing them to a global js-file that later gets served, so the structure looks like this?
home.js
//home specific jquery functions
table.js
//table specific jquery functions
client.js
import home.js
import table.js
index.html
<script src="js/client.js" defer ></script>

Using dynamic data to plot Chart.js but show cant read property "skip" of undefined

i am new to angular js and chart js. I want to plot graph with chart js with dynamic data, here is the result when server return:
I get the "nameArray" and "values" from the server and want to put inside chart.js
$scope.drawChart = function () {
console.log("start draw");
var name = $scope.result.nameArray
var value = $scope.result.values
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'bar',
// The data for our dataset
data: {
labels: name,
datasets: [{
// label: "My First dataset",
label: name,
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
// data: [0, 10, 5, 2, 20, 30, 45],
data: value,
}]
},
// Configuration options go here
options: {}
});
}
And my angular controller part:
$scope.result = [];
$scope.getPosts = function () {
$http({
method: 'POST',
url: 'http://localhost/test.php',
data: {
"action": "getchartdata",
"username": "username",
"deptname": "departname",
"officename": "office",
"softwarename": "this",
"StartTime": "time",
"EndTime": "time",
"ipaddress": "10.0.90.1"
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
transformRequest: function (data) {
var str = [];
for (var p in data)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(data[p]));
return str.join("&");
}
}).then(function (result) {
$scope.result = result.data
console.log($scope.result);
console.log($scope.result.nameArray)
$scope.drawChart();
}, function (error) {
console.log("error")
});
};
I get this error:
I not sure what happening there, or is that chartjs doest support like this?

Separating results in chartjs line chart

So, I have a form with a starting date, an end date and a selector so you can choose which server (selected by id) you'd like to select data from, and returns a json string with the day, temperature and server id. everything works just fine here.
My issue comes when I tried to make it so when you don't select a server, it gives you all data from all servers (select stuff from table where id like '%'). I adapted my chart generating function to this:
function generateChart(data) {
var results = JSON.parse(data);
if (results.error == true) {
var errCode = results.code;
var errText = results.text;
defineError(errCode, errText);
}
else {
var chartjsTemp = [];
var chartjsDate = [];
if (results.length > 1) {
for (var i = 1; i < results.length; i++) {
chartjsTemp.push(results[i].probeTemp);
chartjsDate.push(results[i].dateProbe);
}
}
else {
alert ("No results!");
}
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 don't know how to adapt the datasets part so if I have an unknown number of servers with different values for data, (might return 3 servers or 5 different servers, depending on the database used) to be generated automatically instead of having to do a dataset for every existing server (which means I'd have to do a function for each database with each server).
Edit: This is an example of what happens if I leave it like this (which obviously is not good): http://imgur.com/a/IgH2c
Edit 2: Okay, doing a for loop like this:
for (i=0; i >= chartjsId.length; i++) {
datasets: [{
label: chartjsId[i],
data: chartjsTemp,
backgroundColor: "rgba(240,240,240,0.5)"
}]
}
didn't work much at all. I get a slim framework error.
What I understand, you have draw all the charts you want and know you want to hide all other and show the selected ones.
We can achieve this through Legends, when user click on the legend its display will toggle from graph.
Or we can achieve like this jsFiddle
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "First",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,20,20,1)",
pointColor: "rgba(220,20,20,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 90]
}, {
label: "Second",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(15,187,25,1)",
pointColor: "rgba(15,187,25,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [38, 55, 50, 65, 35, 67, 54]
}]
};
var options = {
// String - Template string for single tooltips
tooltipTemplate: "<%if (label){%><%=label %>: <%}%><%= value + ' %' %>",
// String - Template string for multiple tooltips
multiTooltipTemplate: "<%= value + ' %' %>",
};
var ctx = document.getElementById("myChart").getContext("2d");
window.myLineChart = new Chart(ctx).Line(data, options);
window.myLineChart.store = new Array();
$('#selectbox').change(function () {
var label = $('#selectbox').val();
var chart = window.myLineChart;
var store = chart.store;
var finded = false;
//Restore all
for (var i = 0; i < store.length; i++) {
var restored = store.splice(i, 1)[0][1];
chart.datasets.push(restored);
}
//Если нет, то добавляем в стор
if (label!='All') {
console.log('Start search dataset with label = ' + label);
for (var i = 0; i < chart.datasets.length; i++) {
if (chart.datasets[i].label === label) {
chart.store.push([label, chart.datasets.splice(i, 1)[0]]);
}
}
}
chart.update();
});

Lightswitch HTML custom control show only once

I've a LS project with one Custom Control where I render a chart with chartjs. The first time I load the page everything is ok, but if I move to another page and then come back the custom control is not rendered anymore (the code is called but nothing appear). I have to press F5 everytime I want to see it!
How can I fix this?
UPDATE:
I've notice that if I set a global variable, when I come back to the screen the variable is not reinizialized .Also another page containing the jquery-week calendar has the same issue. When I navigate away from a screen and later come back I load another instance of the "screen" or only get the old one, with all the stuff already loaded?
here the code
/// <reference path="~/GeneratedArtifacts/viewModel.js" />
function updateGraphs(chart, query, inizio, fine) {
var last = 0;
for (var i = inizio; i <= fine; i.addDays(1)) {
query(i).execute().then(function (res) {
try {
if (chart.datasets[0].points.length > 25)
chart.removeData();
var date = new Date(inizio.valueOf()).addDays(last++);
var str = format_2digit(date.getDate()) + "/" + format_2digit(date.getMonth() + 1) + "/" + date.getFullYear();
chart.addData([res.results.length], last % 5 == 0 ? str : "");
}
catch (e) { alert(e); }
});
}
}
myapp.Home.created = function (screen) {
var now = new Date();
var month = now.getMonth();
var year = now.getFullYear();
screen.GraficoInizio = new Date(year, month, 1);
screen.GraficoFine = new Date(year, month + 1, 0);
};
myapp.Home.GraficoFine_postRender = function (element, contentItem) {
contentItem.dataBind("screen.GraficoInizio", function (value) {
var month = contentItem.screen.GraficoInizio.getMonth();
var year = contentItem.screen.GraficoInizio.getFullYear();
contentItem.value = new Date(year, month + 1, 0);
});
};
myapp.Home.GraficoClienti_render = function (element, contentItem) {
// creo il grafico
$(element).append("<canvas id='chartClienti' width='500px' height='300px' />");
var ctx = $('#chartClienti').get(0).getContext("2d");
var chart = new Chart(ctx);
var data = {
labels: [],
datasets: [
{
label: [],
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: []
}
]
};
chart = chart.Line(data, { animationSteps: 15 });
contentItem.dataBind("screen.GraficoInizio", function (value) {
updateGraphs(chart, myapp.activeDataWorkspace.ApplicationData.AbbonamentiAttivi,contentItem.screen.GraficoInizio, contentItem.screen.GraficoFine);
});
contentItem.dataBind("screen.GraficoFine", function (value) {
updateGraphs(chart, myapp.activeDataWorkspace.ApplicationData.AbbonamentiAttivi, contentItem.screen.GraficoInizio, contentItem.screen.GraficoFine);
});
};
myapp.Home.StampaQRCode_execute = function (screen) {
var popup = window.open("../QRCode.aspx");
popup.focus();
};
Lightswitch does not remove (it hides) html elements from page when you navigate to another page. -> That's how the "Back Button" Works, it shows/set visible the "old page".
When you navigate back to the page in page source you will be able to find more than one "chartClienti" element.
One possible solution is to remove the element if it already exists:
myapp.Home.GraficoClienti_render = function (element, contentItem) {
// creo il grafico
var existedChart = $('#chartClienti');
//element exists if it's length is more than 0
if (existedChart.length > 0) {
existedChart.remove();
}
$(element).append("<canvas id='chartClienti' width='500px' height='300px' />");
var ctx = $('#chartClienti').get(0).getContext("2d");
var chart = new Chart(ctx);
var data = {
labels: [],
datasets: [
{
label: [],
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: []
}
]
};
chart = chart.Line(data, { animationSteps: 15 });
contentItem.dataBind("screen.GraficoInizio", function (value) {
updateGraphs(chart, myapp.activeDataWorkspace.ApplicationData.AbbonamentiAttivi,contentItem.screen.GraficoInizio, contentItem.screen.GraficoFine);
});
contentItem.dataBind("screen.GraficoFine", function (value) {
updateGraphs(chart, myapp.activeDataWorkspace.ApplicationData.AbbonamentiAttivi, contentItem.screen.GraficoInizio, contentItem.screen.GraficoFine);
});
};
Better solution would be following:
A) getting the all elements with that id and updating the latest.
B) give unique id each time you render your control (autoincrement by one: chartClienti0, chartClienti1, ... chartClientiN)
var globalVariableForchartClienti;
myapp.Home.GraficoClienti_render = function (element, contentItem) {
// creo il grafico
var chartClientiElementId = 'chartClienti_' + Math.floor((Math.random() * 999999) + 1);
$(element).append("<canvas id='" + chartClientiElementId + "' width='500px' height='300px' />");
//You can use "globalVariableForchartClienti" to access custom element in any other function
globalVariableForchartClienti = chartClientiElementId;
var ctx = $('#chartClienti').get(0).getContext("2d");
var chart = new Chart(ctx);
var data = {
labels: [],
datasets: [
{
label: [],
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: []
}
]
};
chart = chart.Line(data, { animationSteps: 15 });
contentItem.dataBind("screen.GraficoInizio", function (value) {
updateGraphs(chart, myapp.activeDataWorkspace.ApplicationData.AbbonamentiAttivi,contentItem.screen.GraficoInizio, contentItem.screen.GraficoFine);
});
contentItem.dataBind("screen.GraficoFine", function (value) {
updateGraphs(chart, myapp.activeDataWorkspace.ApplicationData.AbbonamentiAttivi, contentItem.screen.GraficoInizio, contentItem.screen.GraficoFine);
});
};

Chart.js - Multiple Line Charts - Only Show Last Chart

I am using chart.js to show multiple line charts on one page. However, only the last chart shows even though I have called them #canvas1 and #canvas2. Something must be conflicting somewhere and I've tried most things but not having any joy. Here are two charts, it only shows the last one:
Graph One
<script type="text/javascript">
var lineChartData = {
labels : ["January","February","March","April","May","June","July","August","September","October","November","December"],
datasets : [
{
label: "Target",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [160000,175000,185000,180000,185000,185000,185000,195000,200000,0,0]
},
{
label: "Sales",
fillColor : "rgba(151,187,205,0.2)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(151,187,205,1)",
data : [<?php echo $stockJanuary ?>,<?php echo $stockFebruary ?>,<?php echo $stockMarch ?>,<?php echo $stockApril ?>,<?php echo $stockMay ?>,<?php echo $stockJune ?>,<?php echo $stockJuly ?>,<?php echo $stockAugust ?>,<?php echo $stockSeptember ?>,<?php echo $stockOctober ?>,<?php echo $stockNovember ?>,<?php echo $stockDecember ?>]
}
]
}
window.onload = function(){
var ctx = document.getElementById("canvas1").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
}
</script>
Graph Two:
<script type="text/javascript">
var lineChartData = {
labels : ["January","February","March","April","May","June","July","August","September","October","November","December"],
datasets : [
{
label: "Target",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [19000,21000,23000,25000,27000,29000,31000,32000,33000,0,0]
},
{
label: "Sales",
fillColor : "rgba(151,187,205,0.2)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(151,187,205,1)",
data : [<?php echo $northJanuary ?>,<?php echo $northFebruary ?>,<?php echo $northMarch ?>,<?php echo $northApril ?>,<?php echo $northMay ?>,<?php echo $northJune ?>,<?php echo $northJuly ?>,<?php echo $northAugust ?>,<?php echo $northSeptember ?>,<?php echo $northOctober ?>,<?php echo $northNovember ?>,<?php echo $northDecember ?>]
}
]
}
window.onload = function(){
var ctx = document.getElementById("canvas2").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
}
</script>
Your help would be much appreciated, been bugging me for a while now!
Thanks in advance
Try using different names for the two ctx variables.
window.onload = function(){
var ctx = document.getElementById("canvas2").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
var ctx2 = document.getElementById("canvas1").getContext("2d");
window.myLine = new Chart(ctx2).Line(lineChartData2, {
responsive: true
});
}
Initially I had the exact same problem as the original question and Tried Arpan Das suggestion, but did not get right on the first try.
Anyone else having the same problem, might find it useful to have a look at this working example of multiple graphs on one page:
<div id="canvas-holder">
<canvas id="A" width="300" height="300"/><br>
</div>
<div id="canvas-holder">
<canvas id="B" width="300" height="300"/><br>
</div>
<script>
var pieDataA = [ { value: 50, color: "#F6BFBD" } ];
var pieDataB = [ { value: 50, color: "#00BFBD" } ];
window.onload = function(){
var ctx1 = document.getElementById("A").getContext("2d");
window.myPieA = new Chart(ctx1).Pie(pieDataA);
var ctx2 = document.getElementById("B").getContext("2d");
window.myPieB = new Chart(ctx2).Pie(pieDataB); };
</script>
Fiddle link: http://fiddle.jshell.net/2omjx9dn/
The mistake in the initial code is that you call the function window.onload multiple times.
Unfortunately, it's not that simple. The first onload event handler will be replaced when the second onload event handler is executed. [and so one untill last onload.window]
That problem usually appears when you want to create the graphs separately and, for example, include with php in your page graphs (because in each php page you are calling window.onload)
Easy solution:
function start() {
func1();
func2();
}
window.onload = start;
Simon Willison proposed:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
/* more code to run on page load */
});
Multiple Line charts using chart.js
<script type="text/javascript">
$(document).ready(function () {
debugger;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CampComparison.aspx/getLineChartDataload",
data:{},
async: true,
cache: false,
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
})
function OnSuccess_(reponse) {
var aData = reponse.d;
var aLabels = aData[0];
var aDatasets1 = aData[1];
var aDatasets2 = aData[2];
var aDatasets3 = aData[3];
var aDatasets4 = aData[4];
var aDatasets5 = aData[5];
var lineChartData = {
labels: aLabels,
datasets: [
{
label: "Data1",
//fill:false,
fillColor: "rgba(0,0,0,0)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(200,122,20,1)",
data: aDatasets1
},
{
label: "Data2",
fillColor: 'rgba(0,0,0,0)',
strokeColor: 'rgba(220,180,0,1)',
pointColor: 'rgba(220,180,0,1)',
data: aDatasets2
},
{
label: "Data5",
fillColor: "rgba(0,0,0,0)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(152,188,204,1)",
data: aDatasets3
},
{
label: "Data4",
fillColor: 'rgba(0,0,0,0)',
strokeColor: 'rgba(151,187,205,1)',
pointColor: 'rgba(151,187,205,1)',
data: aDatasets4
},
{
label: "Data4",
fillColor: 'rgba(0,0,0,0)',
strokeColor: 'rgba(151,187,205,1)',
pointColor: 'rgba(151,187,205,1)',
data: aDatasets5
},
]
}
Chart.defaults.global.animationSteps = 50;
Chart.defaults.global.tooltipYPadding = 16;
Chart.defaults.global.tooltipCornerRadius = 0;
Chart.defaults.global.tooltipTitleFontStyle = "normal";
Chart.defaults.global.tooltipFillColor = "rgba(0,160,0,0.8)";
Chart.defaults.global.animationEasing = "easeOutBounce";
Chart.defaults.global.responsive = true;
Chart.defaults.global.scaleLineColor = "black";
Chart.defaults.global.scaleFontSize = 16;
//lineChart.destroy();
//document.getElementById("canvas").innerHTML = ' ';
//document.getElementById("chartContainer").innerHTML = ' ';
//document.getElementById("chartContainer").innerHTML = '<canvas id="canvas" style="width: 650px; height: 350px;"></canvas>';
//var ctx = document.getElementById("canvas").getContext("2d");
//ctx.innerHTML = "";
//var pieChartContent = document.getElementById('pieChartContent');
//pieChartContent.innerHTML = ' ';
//$('#pieChartContent').append('<canvas id="canvas" width="650px" height="350px"><canvas>');
//ctx = $("#canvas").get(0).getContext("2d");
var ctx = document.getElementById("canvas").getContext("2d");
var lineChart = new Chart(ctx).Line(lineChartData, {
bezierCurve: true,
chartArea: { width: '62%' },
responsive: true,
pointDotRadius: 10,
scaleShowVerticalLines: false,
scaleGridLineColor: 'black'
});
}
function OnErrorCall_(repo) {
//alert(repo);
}
});
//});
</script>
C#code
--------
[WebMethod(EnableSession = true)]
public static List<object> getLineChartDataload()
{
List<object> iData = new List<object>();
List<string> labels = new List<string>();
string advertiserid = HttpContext.Current.Session["AccountID"].ToString();
if (!string.IsNullOrEmpty(advertiserid))
{
// string StartDate = DateTime.Now.AddDays(-180).ToString("yyyy-MM-dd");
string StartDate = DateTime.Now.AddDays(-60).ToString("yyyy-MM-dd");
string EndDate = DateTime.Now.ToString("yyyy-MM-dd");
string strcampaignid = string.Empty;
DataTable dt = new DataTable();
int i = 0;
chatBL objcampid = new chatBL();
string query = "select distinct top 3 Campaignid,CampaignName from campaign where advertiserid='" + advertiserid + "' order by CampaignName";
dt = objcampid.commonFuntionGetData2(query);
foreach (DataRow drow in dt.Rows)
{
strcampaignid += drow["Campaignid"].ToString() + ",";
}
if (!string.IsNullOrEmpty(strcampaignid))
{
strcampaignid = strcampaignid.Substring(0, strcampaignid.Length - 1);
}
string[] campaignid = strcampaignid.Split(',');
//First get distinct Month Name for select Year.
// string query1 = "select top 10 cast(createddatetime as date) as month_name from advertiser where CurrentBal>0 order by CurrentBal";
//query1 += " ";
// query1 += " order by month_number;";
foreach (string strcamp in campaignid)
{
if (i == 0)
{
chatBL objblabel = new chatBL();
// DataTable dtLabels = objblabel.Topupmonthly("5E8EF1E9-67BF-489C-84CB-AFF0BB0FE707", "2015-09-18", "2016-02-25", "months");
DataTable dtLabels = objblabel.Topupmonthly2(strcamp, StartDate, EndDate, "months");
foreach (DataRow drow in dtLabels.Rows)
{
labels.Add(drow["InsDateTime"].ToString().Substring(2, 7));
}
iData.Add(labels);
}
// string query_DataSet_1 = "select top 10 CurrentBal from advertiser where CurrentBal>0 order by CurrentBal";
//query_DataSet_1 += " (orders_quantity) as total_quantity from mobile_sales ";
//query_DataSet_1 += " where YEAR(orders_date)='" + year + "' and mobile_id='" + mobileId_one + "' ";
//query_DataSet_1 += " group by month(orders_date) ";
//query_DataSet_1 += " order by month_number ";
chatBL objbl = new chatBL();
DataTable dtDataItemsSets_1 = objbl.Topupmonthly2(strcamp, StartDate, EndDate, "months");
List<double> lst_dataItem_1 = new List<double>();
foreach (DataRow dr in dtDataItemsSets_1.Rows)
{
lst_dataItem_1.Add(Convert.ToDouble(dr["CPACOUNT"].ToString()));
}
iData.Add(lst_dataItem_1);
//string query_DataSet_2 = "select top 10 Totalspent from advertiser where CurrentBal>0 order by CurrentBal";
//query_DataSet_2 += " (orders_quantity) as total_quantity from mobile_sales ";
//query_DataSet_2 += " where YEAR(orders_date)='" + year + "' and mobile_id='" + mobileId_two + "' ";
//query_DataSet_2 += " group by month(orders_date) ";
//query_DataSet_2 += " order by month_number ";
//chatBL objbl1 = new chatBL();
//DataTable dtDataItemsSets_2 = objbl1.Topupmonthly("5E8EF1E9-67BF-489C-84CB-AFF0BB0FE707", "2015-09-18", "2016-02-25", "months");
//List<double> lst_dataItem_2 = new List<double>();
//foreach (DataRow dr in dtDataItemsSets_2.Rows)
//{
// lst_dataItem_2.Add(Convert.ToDouble(dr["CPACOUNT"].ToString()));
//}
//iData.Add(lst_dataItem_2);
i = i + 1;
}
}
return iData;
}
I was having the same issue and although it was a minor lack of attention from my part, it took me a while to figure it out: I was using the same data reference for all charts with small changes.
Here is the problem and solution:
chartData = {
labels: Array(dataLeft.length).fill(""), // No labels on X axis
datasets: [
{
label : "Lado Esquerdo",
backgroundColor : "rgba(50,192,50,0.4)",
borderColor : "rgba(75,192,75,1)",
pointBorderColor : "rgba(75,192,75,1)",
data : dataLeft,
},
{
label : "Lado Direito",
backgroundColor : "rgba(192,50,50,0.4)",
borderColor : "rgba(192,75,75,1)",
pointBorderColor : "rgba(192,75,75,1)",
data : dataRight,
}
]
};
I was using this chartData for all charts, but before constructing a new chart, I was changing the data attribute (chartData.datasets[0].data = some_specific_value_for_each_chart)
But since this is a reference, I was changing the data of all the previously constructed charts, setting their data to the same data of the last chart initialized!
I don't know if I took the best approach, but to solve this I returned the data dynamically when initializing the charts
createChartData = function(dataRight, dataLeft) {
return {
labels: Array(dataLeft.length).fill(""), // No labels on X axis
datasets: [
{
label : "Lado Esquerdo",
backgroundColor : "rgba(50,192,50,0.4)",
borderColor : "rgba(75,192,75,1)",
pointBorderColor : "rgba(75,192,75,1)",
data : dataLeft,
},
{
label : "Lado Direito",
backgroundColor : "rgba(192,50,50,0.4)",
borderColor : "rgba(192,75,75,1)",
pointBorderColor : "rgba(192,75,75,1)",
data : dataRight,
}
]
}
};
And then to init the chart:
var chart1 = new Chart(ctx1, {
type: 'line',
data: createChartData(graphData1, graphData2),
options: chartOptions
});

Categories

Resources