using JavaScriptSerializer - javascript

in my asp.net webform application i want to send a variable from my codebehind to the .aspx page for using in my js codes
codebehind:
public string GetSomestring()
{
JavaScriptSerializer j = new JavaScriptSerializer();
return j.Serialize("#000");
}
and in my page in js i have this code
<script>
var randomScalingFactor = function () { return Math.round(Math.random() * 100) };
var color= '<%= GetSomestring()%>';
var lineChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: color,
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [12,23,12,43,10,3]
}
]
}
window.onload = function () {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
}
</script>
the string returned to my .aspx page because when i write the below code it execute rightly
var color = '<%= GetSomestring()%>';
alert(color);
and when i write this code my js execute rightly
var color = "#000";
i dont know what is the problem that my first code not execute rightly and pointStrokeColor not get the "color"

To get value from server in javascript you should use Ajax for that using webmethod in codebehind.
Here is some sample code may it help you.
Code Behind:
[WebMethod]
public string GetSomestring()
{
JavaScriptSerializer j = new JavaScriptSerializer();
return j.Serialize("#000");
}
View: "Client Side"
var result;
$.ajax({
url: ../PageName/GetSomestring",
type: "get",
dataType: "json",
contentType: "application/json;charset=utf-8",
success: function (data, status) {
result = data.d;
},
error: function (requeset, status, error) {
alert(error);
}
});
var color= result ;
OR just try this:
Convert color into color.value
<script>
var randomScalingFactor = function () { return Math.round(Math.random() * 100) };
var color= '<%= GetSomestring()%>';
var lineChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: color.value,
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [12,23,12,43,10,3]
}
]
}
window.onload = function () {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
}
Convert color into color.value
pointStrokeColor: color.value,
Hopefully this will help you.Thanks

Related

Pug - Access data from server in pug script(type='text/javascript')

I am trying to load data from the server in my pug template.
My route looks like the following:
app.get('/serverdata', async(req, res) => {
const chartData = []
for (const i = 0; i < 7; i++) {
chartData.push(Math.random() * 50)
}
const result = JSON.stringify(chartData)
res.render('serverdata', {
result,
})
})
My pug template looks like the following:
.row
.col-md-12
.card
.embed-responsive.embed-responsive-16by9
canvas#myNewChart(style='display: block; width: 1000px; height: 500px;', width='1000', height='500')
block specific-js
script(type='text/javascript', src="js/plugins/chart.js")
script(type='text/javascript').
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
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: result //here I am getting the error
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(data);
My error is within my view file:
serverdata:13 Uncaught ReferenceError: result is not defined
at serverdata:13
Any suggestions how to load server data in the script. tag of my pug file?
I appreciate your replies!
I think you are mixing different contexts. The line that gives you an error is executed in the browser, and in that context, there is no variable named result.
Since you have a endpoint /serverdata on your server in place, all you need to load and parse the data from that URL. Details depend on what kinds of JavaScript libraries you are using, but with jQuery getJSON:
$.getJSON("/serverdata", function(data) {
/* Update your chart by using 'data' */
});

I don't want to auto reflect chart with $watch in angulars js?

Right now I am implementing line chart in angular js. And I have written one directive for this, So it is working fine, But when I am putted $watch in this directive then every time chart will updating continuously. I want to use $watch for some dynamic change after loaded the page.
angular.module('app.abc').directive('linechart', function () {
return {
restrict: 'A',
template:'',
link: function (scope, element, attributes) {
scope.$watch(function(){
var lineOptions = {
scaleShowGridLines : true,
scaleGridLineColor : "rgba(0,0,0,.05)",
scaleGridLineWidth : 1,
bezierCurve : true,
};
var lineData = { labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My Second dataset",
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: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var ctx = element[0].getContext("2d");
var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
})
}
}
});
<canvas style="display: block;" linechart height="120" ></canvas>
Line chart reflecting updates is contiguously. But I don't want to reflection continuously. I have tried to put my ctx object outside of $watch, but chart is not showing anything. Actually I am new in angular js and also new in directives. Please give me idea how handle this directive with $watch. I have seen one demo(based on javascript) example https://codepen.io/SitePoint/pen/mJRrKw

Labeling and Data (ChartJS)

I am working on a code with an API. I need to create a line chart for these things called tickets. I need to call the information for them from the API. It has the ticket ID, date, and description. For the labeling, I have four weeks of the month. If I don't call it for every week, the chart won't show up. However, when I do this, instead of the information on a chart popping up, an alert does with all of the information for each week.
var lineChartData = {
labels: ["Week 1","Week 2","Week 3","Week 4"],
datasets: [{
label: "Tickets",
fillColor: "rgba(100,200,244,0.2)",
strokeColor: "rgba(100,200,244,1)",
pointColor: "rgba(200,255,255,.7)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [$.get("http://velocity.data.wpengine.com:3000/tickets/", function(data){ alert(JSON.stringify(data));}).fail(function() {alert("FAIL");}), $.get("http://velocity.data.wpengine.com:3000/tickets/", function(data){ alert(JSON.stringify(data));}).fail(function() {alert("FAIL");}), $.get("http://velocity.data.wpengine.com:3000/tickets/", function(data){ alert(JSON.stringify(data));}).fail(function() {alert("FAIL");}), $.get("http://velocity.data.wpengine.com:3000/tickets/", function(data){ alert(JSON.stringify(data));}).fail(function() {alert("FAIL");}) ] };
If you need the full code (this has CSS, HTML, and the JavaScript), click here.
$.get does not evaluate to a return value like a normal function call.
When the data is received from http://velocity.data.wpengine.com:3000/tickets/, your callback function gets called. In your case that is
function(data){ alert(JSON.stringify(data));}
You have access to the returned data inside this callback function. And you're just alerting it. Which is why you simply get an alert alone. You need to move your chart drawing code into this call back function. Something like
window.onload = function () {
$.get("http://velocity.data.wpengine.com:3000/tickets/list/", function(data){
var lineChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
fillColor: "rgba(100,200,244,0.2)",
strokeColor: "rgba(100,200,244,1)",
pointColor: "rgba(200,255,255,.7)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: data,
},
{
label: "My Second dataset",
fillColor: "rgba(100,200,244,0)",
strokeColor: "rgba(100,200,244,0)",
pointColor: "rgba(200,255,255,0)",
pointStrokeColor: "rgba(255,255,255,0)",
pointHighlightFill: "#rgba(255,255,255,0)",
pointHighlightStroke: "rgba(220,220,220,0)",
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
}]
};
var ctx1 = document.getElementById("chart1").getContext("2d");
window.myLine = new Chart(ctx1).Line(lineChartData, {
showScale: false,
pointDot: true,
responsive: true
});
var ctx2 = document.getElementById("chart2").getContext("2d");
window.myLine = new Chart(ctx2).Line(lineChartData, {
responsive: true
});
....

Overlapping graphics

I am trying to develop an admin dashboard with site metrics and I have menues showing different data when you click on them. I write the front-end on Backbone.js and use Jquery to reduce the number of calls. The problem is that when I browse the page and when I open a new graphic and mouse-over it, sometimes it starts to overlap with the previous graphics. What can I do so that I only see the graphic relevant to the option I select?
newAndTotalUsersPerMonth: function (event) {
event.preventDefault();
$('#User').hide();
$('#right').hide();
$('#left').hide();
$('#third').hide();
$('#logLabel').hide();
$('#main-view').addClass('small-2');
$('#main-view').append('<p id="label"></p>');
var $label = $('#label');
var text = $label.text();
$label.text(text.replace(text, "New and total users per month"));
$('#main-view').append('<div id="container" class="row">'+
'<col-md-12>'+
'<div id="canvasArea">'+
'<canvas id="nu1" style="width:960px; height:250px; overflow:hidden;"></canvas>'+
'</div>'+
'</col-md-12>'+
'</div>');
$.ajax({
url: '/analytics',
type: 'GET',
success: function (data) {
var labels = [];
var dataSet1 = [];
var dataSet2 = [];
for (var i = 0; i < data.length; i++) {
labels.push(data[i][1] + "." + data[i][0]);
dataSet1.push(data[i][2]);
dataSet2.push(data[i][3]);
}
var lineData = {
labels: labels,
datasets: [
{
label: "New Users",
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: dataSet1
},
{
label: "Total Users",
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: dataSet2
}
]
};
if(!$('#canvasArea').is(':empty')) {
var ctx = document.getElementById("nu1").getContext("2d");
window.myBar = new Chart(ctx).Line(lineData, {
responsive: false
});
}
else {
$('#nu1').reset();
var ctx = document.getElementById("nu1").getContext("2d");
window.myBar = new Chart(ctx).Line(lineData, {
responsive: false
})
};
}
});
}

chart js tooltip how to control the data that show

I'm using chart.js plugin and using a group chart by bar view.
when i hover a group of bars i can see a tooltip that show me the data of this bars.
but i what to change the tooltip to show my only single data when I'll hover the bar data.
and I what to show diffrent data info.
jsfiddle example
var ctx = document.getElementById("errorChart").getContext("2d");
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [65, 0, 0, 0, 0, 0, 0]
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var myBarChart = new Chart(ctx).Bar(data);
You could extend the bar graph to include this functionality. By default it will return both bars at the index you have hovered over, it will also check for multiple bars at the area you hovered before creating the tooltip and put any extras in that were missing.
So to do this you will need to override two functions getBarsAtEvent and showToolTip here is an example and fiddle
I have tried to make it clear the two important areas that have changed look at the comments in the extended bar type. Small changes were also made to any reference of the helpers as before they were within the scope but now they need to explicitly call Chart.helpers
Chart.types.Bar.extend({
name: "BarOneTip",
initialize: function(data){
Chart.types.Bar.prototype.initialize.apply(this, arguments);
},
getBarsAtEvent : function(e){
var barsArray = [],
eventPosition = Chart.helpers.getRelativePosition(e),
datasetIterator = function(dataset){
barsArray.push(dataset.bars[barIndex]);
},
barIndex;
for (var datasetIndex = 0; datasetIndex < this.datasets.length; datasetIndex++) {
for (barIndex = 0; barIndex < this.datasets[datasetIndex].bars.length; barIndex++) {
if (this.datasets[datasetIndex].bars[barIndex].inRange(eventPosition.x,eventPosition.y)){
//change here to only return the intrested bar not the group
barsArray.push(this.datasets[datasetIndex].bars[barIndex]);
return barsArray;
}
}
}
return barsArray;
},
showTooltip : function(ChartElements, forceRedraw){
console.log(ChartElements);
// Only redraw the chart if we've actually changed what we're hovering on.
if (typeof this.activeElements === 'undefined') this.activeElements = [];
var isChanged = (function(Elements){
var changed = false;
if (Elements.length !== this.activeElements.length){
changed = true;
return changed;
}
Chart.helpers.each(Elements, function(element, index){
if (element !== this.activeElements[index]){
changed = true;
}
}, this);
return changed;
}).call(this, ChartElements);
if (!isChanged && !forceRedraw){
return;
}
else{
this.activeElements = ChartElements;
}
this.draw();
console.log(this)
if (ChartElements.length > 0){
//removed the check for multiple bars at the index now just want one
Chart.helpers.each(ChartElements, function(Element) {
var tooltipPosition = Element.tooltipPosition();
new Chart.Tooltip({
x: Math.round(tooltipPosition.x),
y: Math.round(tooltipPosition.y),
xPadding: this.options.tooltipXPadding,
yPadding: this.options.tooltipYPadding,
fillColor: this.options.tooltipFillColor,
textColor: this.options.tooltipFontColor,
fontFamily: this.options.tooltipFontFamily,
fontStyle: this.options.tooltipFontStyle,
fontSize: this.options.tooltipFontSize,
caretHeight: this.options.tooltipCaretSize,
cornerRadius: this.options.tooltipCornerRadius,
text: Chart.helpers.template(this.options.tooltipTemplate, Element),
chart: this.chart
}).draw();
}, this);
}
return this;
}
});
then to use it just do what you did before but use BarOneTip (call it whatever you like, what ever is in the name attribute of the extended chart will be available to you.
var ctx = document.getElementById("errorChart").getContext("2d");
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [65, 0, 0, 0, 0, 0, 0]
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var myBarChart = new Chart(ctx).BarOneTip(data);
I should mention that if chartjs gets updated you would need to manually put any changes to the functions into the overridden ones

Categories