score:19
retrieving data from database multiple-line charts in chart.js using asp.net,c# here is the code
<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;
}
score:22
you were creating inserting the same object (dataset) at all 4 locations of the dataset. so any manipulations in the loop are being done on all of the array elements (actually it would be more accurate to say that it's being done on dataset and that dataset is there at all 4 indices of the array)
notice that in the following code the {} object literal is actually being inserted 4 times into the array giving you a fresh element each time.
linechartdata = {}; //declare an object
linechartdata.labels = []; //add 'labels' element to object (x axis)
linechartdata.datasets = []; //add 'datasets' array element to object
for (line = 0; line < 4; line++) {
y = [];
linechartdata.datasets.push({}); //create a new line dataset
dataset = linechartdata.datasets[line]
dataset.fillcolor = "rgba(0,0,0,0)";
dataset.strokecolor = "rgba(200,200,200,1)";
dataset.data = []; //contains the 'y; axis data
for (x = 0; x < 10; x++) {
y.push(line + x); //push some data aka generate 4 distinct separate lines
if (line === 0)
linechartdata.labels.push(x); //adds x axis labels
} //for x
linechartdata.datasets[line].data = y; //send new line data to dataset
} //for line
ctx = document.getelementbyid("chart1").getcontext("2d");
mylinechart = new chart(ctx).line(linechartdata);
// for chart.js 2.0 the following will be to create `mylinechart`
// mylinechart = new chart(ctx1, {
// type: 'line',
// data: linechartdata,
// });
i also made a small change for your labels - you just need 1 set of labels.
to draw an analogy, the original code was doing this
series a = new series()
array chartdata = []
for (var i = 0; i < 4; i++) {
chartdata.add(a);
-- some modifications on a ---
}
at the end of this you basically have an array with 4 pointers to the same object a
.
fiddle - http://jsfiddle.net/tk78bosy/
Source: stackoverflow.com
Related Query
- create a multi line chart using Chart.js
- How to create a line on a chart using chartjs-plugin-annotation
- Create a line chart using an user input table from a data table in chart.js
- how to create line chart using chart.js in angular 2+
- Using custom dataformat in chart.js for Multi Axis Line Chart
- How can I create a horizontal scrolling Chart.js line chart with a locked y axis?
- Moving vertical line when hovering over the chart using chart.js
- How to add an on click event to my Line chart using Chart.js
- Display line chart with connected dots using chartJS
- How to create stacked bar chart using react-chartjs-2?
- Display a limited number of labels only on X-Axis of Line Chart using Chart.js
- How to create a gradient fill line chart in latest Chart JS version (3.3.2)?
- How to create single value Doughnut or Pie chart using Chart.js?
- Create multiple dynamic stacked chart using chart.js in Angular 10?
- chartjs - multi axis line chart - cannot read property 'min' of undefined
- How to create a gantt chart using Chart.js and populate dates?
- Create Chart using Reactjs Chartjs and axios
- Add data to line chart using chart.js
- Change Axis Line color in Chart created using chart.js
- Displaying line chart for multiple months using chart.js
- How to make aspecific API call from within a Line Chart class in ReactJS using react-chartjs-2?
- Chart JS: Always show tooltips in a multi dataset line chart
- display vertical axis label in line chart using chart.js
- how can i use chart.js to create a chart that has one time series line and one linear line on it at the same time?
- create Chart using Chartjs and PHP
- Adding data to line chart using addData() method in Chart.js
- How to create Waterfall model chart using QuickChart?
- How to create a bar and a line in a same graph using chart.js in React?
- How to create a line chart indicating which month a user wrote more or less blogs?
- Line Chart using Chart js with time data
More Query from same tag
- ChartJS: chart not show all data
- Modify the labels in chart.js when I update the chart
- chart.js TypeError: item is null
- Not able to pass array of data to chart.js in React
- In react.js with chart.js, I can't access to my data in a componant
- Use of ng-class with Chart.js
- How to render Chart.js 2.x tooltips on top of everything
- How to plot a line graph with x and y data
- Charts.js graph not displaying
- HorizontalBar chart is displayed below canvas when I set height with style attribute for chart div (Chart.js 2.9.4)
- React chartjs 2 - Type 'string' is not assignable to type '"timeseries"'
- In Chart.js I want to show dotted gridLines like in below image
- How put dataset labels into multiTooltipTemplate?
- Label not showing in Chart.js with Grails
- Can't change color line with chart.js
- Hover over chart shows multiple datapoints
- Chart.js How should I do to make vertical dotted line
- Change the font size of chart.js with chartkick
- Cannot find module 'chart.js'
- Chart.js does not display any data
- Chartjs barchart generate data for an array dataset
- Chart.js - x-axis and tooltip label shows "undefined" in Chrome when browser language is NOT English
- charts.js show dates 1 year
- Unable to pass on data from json file to labels and datasets in chart.js
- Flask with Chart JS Scatter Plot struggle
- Is it possible to get the assigned ref name in a component? Vue.js
- Get the data from node.js for Chart.js
- Remove redundant legends on the chart using generateLabels with ChartJS v3
- Unable to see the lines in chart.js
- Why my ajax function does not work on yii2