How build array("key":value) in js with loop json ajax - javascript

I’m trying to modify a vector map with values obtained by AJAX and JSON.
Map function perfect with this array key value:
var visitorsData = {
"tac": 564,
"moq": 400,
"lim": 1000,
"apu": 800,
"caj": 760,
"ama": 300,
"lib": 700,
"lam": 600,
};
And the function that takes this values is this:
$('#world-map').vectorMap({
map: 'peru',
backgroundColor: '#fff',
regionStyle: {
initial: {
fill: "#c6c6c6",
stroke: "#204d6f",
"stroke-width": 1,
"stroke-opacity": 1
},
hover: {
fill: "#ed0000",
"fill-opacity": "1"
}
},
series: {
regions: [{
values: visitorsData,
scale: ["#3c8dbc", "#2D79A6"], //['#3E5E6B', '#A6BAC2'],
normalizeFunction: 'polynomial'
}]
},
onRegionLabelShow: function(e, el, code) {
if (typeof visitorsData[code] != "undefined")
el.html(el.html() + ': ' + visitorsData[code] + ' new visitors');
}
})
Now I want to take values taken from a JSON and with this build a new visitorsData but no function. This is my code:
$.ajax({
url: globalMapUrl, //obtain json
})
.done(function(data) {
var visitorsData = new Array();
for (var i = 0; i < data.length; i++) {
var item = data[i];
visitorsData[item.nombre] = item.numeroDeAnuncios;
}
})
.fail(function() {
alert("Ajax failed to fetch data")
})

Your visitorsData looks like a json object not a vector array
Create a new JSONObject instead of an Array and you should be good
instead of,
var visitorsData = new Array();
try
var visitorData = {};

Related

Code efficiency using VectorGrid in Leaflet

I have about 7 000 polygons in a GeoJSON file using VectorGrid, all is fine using one layer but I need to split this layer into 10 LayerGroups (10 regions with their own polygons). How can this be done without rewriting the code 10 times? That seems to be lots of waste, there must be a smarter way and I can't figure it out. This is the code Im testing with, the highlight has to be working with all 11 layers...
var all_regions = new L.layerGroup();
var region_1 = new L.layerGroup();
var region_2 = new L.layerGroup();
var region_3 = new L.layerGroup();
/* snip */
var region_10 = new L.layerGroup();
var highlight_polygon;
var clearHighlight = function () {
if (highlight_polygon) {
vectorGrid.resetFeatureStyle(highlight_polygon);
}
highlight_polygon = null;
};
var vectorTileOptions_allRegions = {
rendererFactory: L.canvas.tile,
maxNativeZoom: 13,
zIndex: 6,
vectorTileLayerStyles: {
sliced: {
weight: 2,
color: "gray",
opacity: 1,
fill: false,
//fillColor: 'white',
//stroke: true,
fillOpacity: 0,
},
},
interactive: true,
getFeatureId: function (f) {
return f.properties.id;
},
};
var vectorTileOptions_region_1 = {
rendererFactory: L.canvas.tile,
maxNativeZoom: 13,
zIndex: 6,
vectorTileLayerStyles: {
sliced: function (properties, zoom) {
var region = properties.region;
if (region === "region one") {
return {
weight: 2,
color: "gray",
opacity: 1,
fill: false,
//fillColor: 'white',
//stroke: true,
fillOpacity: 0,
};
} else {
return {
weight: 0,
opacity: 0,
fill: false,
stroke: false,
fillOpacity: 0,
interactive: false,
};
}
},
},
interactive: true,
getFeatureId: function (f) {
return f.properties.id;
},
};
// Next vectorTileOptions until all 11 of them....
$.getJSON("/data/regions.geojson", function (json) {
//Not sure this is the correct way doing it...
var vectorGrid = L.vectorGrid
.slicer(json, vectorTileOptions_allRegions, vectorTileOptions_region_1)
.on("click", function (e) {
var properties = e.layer.properties;
L.popup()
.setContent(
"<b>Name</b>: " +
properties.region_name +
"<br><b>Date</b>: " +
"<i>" +
properties.date +
"</i>"
)
.setLatLng(e.latlng)
.openOn(map);
clearHighlight();
highlight_polygon = e.layer.properties.id;
vectorGrid.setFeatureStyle(highlight_polygon, {
weight: 3,
color: "gray",
opacity: 1,
fillColor: "#ff9999",
fill: true,
radius: 6,
fillOpacity: 0.3,
});
L.DomEvent.stop(e);
});
var clearHighlight = function () {
if (highlight_polygon) {
vectorGrid.resetFeatureStyle(highlight_polygon);
}
highlight_polygon = null;
map.on("popupclose", clearHighlight);
};
//This will not work....
vectorGrid.addTo(all_regions);
vectorGrid.addTo(region_1);
});
You probably want to do something like...
var regions = []; // An array that will hold instances of VectorGrid
var vectorGridOptions = {
rendererFactory: L.canvas.tile,
maxNativeZoom: 13,
zIndex: 6,
vectorTileLayerStyles: {
sliced: {}, // Empty, because it shall be overwritten later.
},
};
var defaultStyle = {
stroke: true,
weight: 2,
};
var regionStyles = [];
regionStyles[0] = {
weight: 2,
color: "gray",
};
regionStyles[1] = {
weight: 1,
color: "red",
};
/* ...etc, up to regionStyles[9] */
fetch("/data/regions.geojson")
.then(function (response) { return response.json(); })
.then(function (json) {
// For each number between 0 and 9...
for (var i = 0; i <= 9; i++) {
// Assuming that the GeoJSON data holds a FeatureCollection,
// create a copy of said GeoJSON FeatureCollection, but holding only
// the wanted features.
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
var filteredGeoJSON = {
type: "FeatureCollection",
features: json.features.filter(function (feature) {
// This assumes that each Feature has a "regionID" property with a
// numeric value between 0 and 9.
return feature.properties.regionID === i;
}),
};
// Build up the options for the i-th VectorGrid by merging stuff together.
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
var fullRegionStyle = Object.assign({}, defaultStyle, regionStyles[i]);
// Overwrite some stuff in vectorGridOptions. Note that this changes the value of
// a piece of vectorGridOptions at each pass of the loop.
vectorGridOptions.vectorTileLayerStyles.sliced = fullRegionStyle;
regions[i] = L.vectorGrid.slicer(filteredGeoJSON, vectorTileOptions);
regions[i].addTo(map);
}
});
The key points here are:
Use a loop to iterate from 1 through 10
Keep things in numbered arrays instead of similarly-named variables
Filter the FeatureCollection, so each VectorGrid works with less data. Drawing invisible polygons/polylines would take as much computing time as drawing visible ones.
Refactor as much as possible, then build up concrete data structures (Object.assign, clone objects if needed)

Live Update Callback -> afterTitle with Array via JSON file

I'm working on a chart, I'm live updating the Chart every 5 seconds that the data comes in. I could manage to get the info from the database and update it really easy, but I just came across a problem with involves setting a path to a part of the chart, in the case: options->tootltips->callbacks->afterTitle and inside of it create an array and pass the array from the JSON to an array inside the callback.
What I would need to do, In a really brief way is, since I already made a function to update the info from my Data and Labels, somehow I will need to make inside this function, a path to the afterTitle, than I will be able send the fifth array, in with stores the data. As you can see in my function, I could manage to do it for the data and label.
I can't have another function that updates, so basically I can't have 2 loadData(), because it makes the Chart blink every time it updates, and that's not what I'm aiming for (The chart can't blink).
Inside this patch, I made an example that didn't work, with is the //:
$.getJSON('loadchart.php', function(response) {
myLineChart.data.datasets[0].data = response[0];
myLineChart.data.datasets[1].data = response[1];
myLineChart.data.datasets[2].data = response[2];
myLineChart.data.datasets[3].data = response[3];
myLineChart.data.labels = response[4];
//The response array that I need is response[5];
//myLineChart.options.tooltips.callbacks[1] = return response[tooltipItem[0]['index']];
myLineChart.update();
});
All my Chart so you can see the path:
<script>
function loadData() {
$.getJSON('loadchart.php', function(response) {
myLineChart.data.datasets[0].data = response[0];
myLineChart.data.datasets[1].data = response[1];
myLineChart.data.datasets[2].data = response[2];
myLineChart.data.datasets[3].data = response[3];
myLineChart.data.labels = response[4];
myLineChart.update();
});
}
loadData();
setInterval(loadData, 5000);
var lbl = [];
var ctx1 = document.getElementById('mychart1').getContext('2d');
var myLineChart = new Chart(ctx1, {
type: 'line',
data: {
labels: lbl,
datasets: [
{
label: "Corrente 1",
data: [],
borderWidht: 6,
borderColor: 'red',
backgroundColor: 'transparent'
},
{
label: "Corrente 2",
data: [],
borderWidht: 6,
borderColor: 'blue',
backgroundColor: 'transparent'
},
{
label: "Corrente 3",
data: [],
borderWidht: 6,
borderColor: 'green',
backgroundColor: 'transparent'
},
{
label: "Corrente Total",
data: [],
borderWidht: 6,
borderColor: 'black',
backgroundColor: 'transparent'
},
]
},
options: {
animation:{
update: 0
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
gridLines: {
display: false
}
}]
},
title: {
display: true,
fontSize: 20,
text: "Gráfico das Correntes"
},
labels: {
fontStyle: "bold",
},
layout: {
padding: {
left: 0,
right: 0,
top: 0,
bottom: 0
}
},
tooltips: {
enabled: true,
mode: 'single',
responsive: true,
backgroundColor: 'black',
titleFontFamily: "'Arial'",
titleFontSize: 14,
titleFontStyle: 'bold',
titleAlign: 'center',
titleSpacing: 4,
titleMarginBottom: 10,
bodyFontFamily: "'Mukta'",
bodyFontSize: 14,
borderWidth: 2,
borderColor: 'grey',
callbacks:{
title: function(tooltipItem, data) {
return data.labels[tooltipItem[0].index];
},
afterTitle: function(tooltipItem, data) {
var tempo = [];
return tempo[tooltipItem[0]['index']];
},
label: function(tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].label || '';
if (label) {
label += ': ';
}
label += (tooltipItem.yLabel)+"A";
return label;
}
}
},
aspectRatio: 1,
maintainAspectRatio: false
}
});
</script>
The part I need is this one:
afterTitle: function(tooltipItem, data) {
var tempo = [];
return tempo[tooltipItem[0]['index']];
This will display a clock but you can also set it to 5000 seconds and call your chart update. Which i would suggest to put in some kind of AJAX to let it work asynchonous.
<!DOCTYPE html>
<html>
<head>
<script>
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500); //<---- !!!
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
As you mention in afterTitle function you want to create an array and pass the array from the JSON to an array inside the callback, and the missing part is you are creating an array tempo and treating it like an object tempo[tooltipItem[0]['index']];, but what you need to do is push this object tooltipItem[0]['index'] to tempo array.
Please replace afterTitle function with the below code
afterTitle: function(tooltipItem, data) {
var tempo = [];
return tempo.push(tooltipItem[0]['index']);

Getting data from a Javascript Object Array in Node js?

I am trying to parse data from a JS Object array and get the value by passing field names and then saving the data in an array. But for some reason, I am not getting the right results. This is what I tried so far. I tried logging the results that I get in val and this is what I get.
val:Array[6]
0
:
Object
BankName
:
"IM BANK"
MERCHANTNAME
:
"MPesa"
NO_OF_FAILED_BANK_TRANSACTIONS
:
0
NO_OF_FAILED_SERVICE_TRANSACTIONS
:
2
NO_OF_SUCCESSFUL_TRANSACTIONS
:
28
__proto__
:
Object
1
:
Object
2
:
Object
3
:
Object
4
:
Object
5
:
Object
length
:
6
How Do I parse the data from my val array by passing field names and then store inside my merchantname array etc.
Homepage.js
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js" ></script>
<script src="http://code.highcharts.com/highcharts.js" ></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<div id="container1" style="width:100%; height:400px;"></div>
<div id ="container2" style="height:20px;"></div>
<div id ="container3" style="width:100%; height:400px;"></div>
<script type="text/javascript">
$(document).ready(function () {
var bankid = [ 57, 9912, 9905, 16, 58 ];
var country = ["KENYA", "KENYA", "KENYA", "UGANDA", "UGANDA"];
var counter = 0;
var merchantname = [];
var successtranscs = [];
var failedtranscs = [];
var servicetranscs = [];
var bankname;
var rows =<%-JSON.stringify(Resultset)%>
function initfunc() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/dashboard",
data: JSON.stringify({country: country[counter], bankid: bankid[counter]}),
dataType: "json",
success: function (Result) {
Result = Result.Resultset
// console.log("result", Result);
// console.log("result",Result);
var data = [];
var merchantname = [];
var successtranscs = [];
var failedtranscs = [];
var servicetranscs = [];
var bankname;
$.each(Result, function(item, value){
console.log("val",value);
for (var i in value) {
$.each(value[i], function(item, val){
console.log(val);
for(var i =0;i<val.length;i++)
{
merchantname.push(val[i].merchant_name);
successtranscs.push(val[i].success_transcs);
failedtranscs.push(val[i].failed_transcs);
servicetranscs.push(val[i].service_transcs);
bankname =val[i].bankname;
console.log("merchantname",merchantname);
}
//
})
}
})
// merchantname.push(Result[i].merchant_name);
// successtranscs.push(Result[i].success_transcs);
// failedtranscs.push(Result[i].failed_transcs);
// servicetranscs.push(Result[i].service_transcs);
// bankname = Result[i].bankname;
// console.log("merchantname",merchantname);
StackedChart(bankname, merchantname, successtranscs, failedtranscs, servicetranscs);
merchantname = [];
successtranscs = [];
failedtranscs = [];
servicetranscs = [];
if (counter == country.length - 1) {
counter = -1;
counter++;
}
else {
counter++;
}
},
error: function (Result) {
console.log(Result);
}
});
}
initfunc();
function StackedChart(bank_name,merch_name, succ_val, fail_val, ser_val) {
var myChart = Highcharts.chart('container1', {
chart: {
type: 'column'
},
title: {
text: bank_name
},
xAxis: {
categories: merch_name
},
yAxis: {
min: 0,
title: {
text: 'TransactionStatus'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
},
legend: {
align: 'right',
x: -30,
verticalAlign: 'top',
y: 25,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
borderColor: '#CCC',
borderWidth: 1,
shadow: false
},
tooltip: {
headerFormat: '<b>{point.x}</b><br/>',
pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
}
}
},
series: [{
name: 'Servicefailure',
data: ser_val
}, {
name: 'Failure',
data: fail_val
}, {
name: 'Success',
data: succ_val
}]
});
}
setInterval(initfunc, 2000);
});
</script>
</body>
</html>
Your access keys (marchant_name, success_transcs, ..) are not same with the keys of the objects in the array (MERCHANTNAME, NO_OF_FAILED_BANK_TRANSACTIONS, ...).
Try using the exact same keys:
...
merchantname.push(val[i].MERCHANTNAME);
successtranscs.push(val[i].NO_OF_SUCCESSFUL_TRANSACTIONS);
...
Nested loops in initfunc() look all wrong.
Callback signature
$.each()'s callback signature is (item, index)
Nesting
Do you realise that $.each(function() {...}) is a looping structure in its own right, without the need of a for loop?
You have loops nested at 4-levels. In summary :
$.each(..., { // outer loop (n1 iterations)
for(...) { // first inner loop (n2 iterations)
$.each(..., function(element2, index2) { // second inner loop (n3 iterations)
for() { // third inner loop (n4 iterations)
// Here, inner statements are called n1 x n2 x n3 x n4 times
}
});
}
});
That's not necessarily wrong, but it's very unusual to need loops nested that deeply.
I rather imagine you want :
$.each(Result, function(item) {
$.each(item, function(val) {
merchantname.push(val.merchant_name); // or .MERCHANTNAME?
successtranscs.push(val.success_transcs); // or .NO_OF_SUCCESSFUL_TRANSACTIONS?
failedtranscs.push(val.failed_transcs); // or .NO_OF_FAILED_BANK_TRANSACTIONS?
servicetranscs.push(val.service_transcs); // or .NO_OF_FAILED_SERVICE_TRANSACTIONS?
bankname = val.bankname; // or .BankName?
});
});
or maybe just :
$.each(Result, function(val) {
merchantname.push(val.merchant_name); // or .MERCHANTNAME?
successtranscs.push(val.success_transcs); // or .NO_OF_SUCCESSFUL_TRANSACTIONS?
failedtranscs.push(val.failed_transcs); // or .NO_OF_FAILED_BANK_TRANSACTIONS?
servicetranscs.push(val.service_transcs); // or .NO_OF_FAILED_SERVICE_TRANSACTIONS?
bankname = val.bankname; // or .BankName?
});

Unable to pass Json data into ajax success call in asp.net mvc

i have made an application in mvc dot net using highcharts
i have connected them to DB and showed them in view
till now every thing is running fine
but now i want to do is that if DB is updated the charts will be automatically show the updated data. for now i have to refresh the page to view updated data and it's showing well but all i want is not refresh it.
i have searched many articles and found than ajax polling should help me out so in my controller code i have passed all data in ViewData coming from reader
while (reader.Read())
{
energy_kwh.Add(Convert.ToDouble(reader["Energy_kWh"]));
power_kw.Add(Convert.ToDouble(reader["Power_kW"]));
voltage_1.Add(Convert.ToDouble(reader["Voltage_Phase_1"]));
voltage_2.Add(Convert.ToDouble(reader["Voltage_Phase_2"]));
voltage_3.Add(Convert.ToDouble(reader["Voltage_Phase_3"]));
current_1.Add(Convert.ToDouble(reader["Current_Phase_1"]));
current_2.Add(Convert.ToDouble(reader["Current_Phase_2"]));
current_3.Add(Convert.ToDouble(reader["Current_Phase_3"]));
Meter_datetime.Add(sample_con.ConvertToUnixTimestamp(Convert.ToDateTime(reader["Data_Datetime"])));
device_id = Convert.ToInt32(reader["Device_ID"]);
}
ViewData["energy_kwh"] = energy_kwh;
ViewData["Meter_datetime"] = Meter_datetime;
ViewData["power_kw"] = power_kw;
ViewData["voltage_1"] = voltage_1;
ViewData["voltage_2"] = voltage_2;
ViewData["voltage_3"] = voltage_3;
ViewData["current_1"] = current_1;
ViewData["current_2"] = current_2;
ViewData["current_3"] = current_3;
ViewData["x"] = x;
ViewData["events"] = events;
return View();
above 'x' is the sreen width only
in my view i have created a global getSVG method that takes an array of charts as an argument
$(function () { Highcharts.getSVG = function (charts) {
var svgArr = [],
top = 0,
width = 0;
$.each(charts, function(i, chart) {
var svg = chart.getSVG();
svg = svg.replace('<svg', '<g transform="translate(0,' + top + ')" ' );
svg=svg.replace('</svg>', '</g>');
top += chart.chartHeight;
width = Math.max(width, chart.chartWidth);
svgArr.push(svg);
});
return '<svg height="'+ top +'" width="' + width + '" version="1.1" xmlns="http://www.w3.org/2000/svg">' + svgArr.join('') + '</svg>';
};
and also created a global export Charts method that takes an array of charts as an argument, and exporting options as the second argument
Highcharts.exportCharts = function(charts, options) {
// Merge the options
options = Highcharts.merge(Highcharts.getOptions().exporting, options);
// Post to export server
Highcharts.post(options.url, {
filename: options.filename || 'chart',
type: options.type,
width: options.width,
svg: Highcharts.getSVG(charts)
});
};
after that i have arranged data coming from controller like this
var myArrayX_kwh = [];
var myArrayY_kwh = [];
var myArrayY_power = [];
var myArrayY_voltage_1 = [];
var myArrayY_voltage_2 = [];
var myArrayY_voltage_3 = [];
var myArrayY_current_1 = [];
var myArrayY_current_2 = [];
var myArrayY_current_3 = [];
var arry_kwh = [];
var arry_power = [];
var arry_voltage_1 = [];
var arry_voltage_2 = [];
var arry_voltage_3 = [];
var arry_current_1 = [];
var arry_current_2 = [];
var arry_current_3 = [];
then i have 2 for loops that will push data in array like this
#foreach (var st in ViewData["Meter_datetime"] as List<double?>)
{
#:myArrayX_kwh.push(#st);
}
#foreach (var st in ViewData["energy_kwh"] as List<double?>)
{
#:myArrayY_kwh.push(#st);
}
#foreach (var st in ViewData["power_kw"] as List<double?>)
{
#:myArrayY_power.push(#st);
}
#foreach (var st in ViewData["voltage_1"] as List<double?>)
{
#:myArrayY_voltage_1.push(#st);
}
#foreach (var st in ViewData["voltage_2"] as List<double?>)
{
#:myArrayY_voltage_2.push(#st);
}
#foreach (var st in ViewData["voltage_3"] as List<double?>)
{
#:myArrayY_voltage_3.push(#st);
}
#foreach (var st in ViewData["current_1"] as List<double?>)
{
#:myArrayY_current_1.push(#st);
}
#foreach (var st in ViewData["current_2"] as List<double?>)
{
#:myArrayY_current_2.push(#st);
} #foreach (var st in ViewData["current_3"] as List<double?>)
{
#:myArrayY_current_3.push(#st);
}
for (var i = 0; i < myArrayX_kwh.length; i++) {
arry_kwh.push({ x: myArrayX_kwh[i], y: myArrayY_kwh[i], });
arry_power.push({ x: myArrayX_kwh[i], y: myArrayY_power[i], });
arry_voltage_1.push({ x: myArrayX_kwh[i], y: myArrayY_voltage_1[i], });
arry_voltage_2.push({ x: myArrayX_kwh[i], y: myArrayY_voltage_2[i], });
arry_voltage_3.push({ x: myArrayX_kwh[i], y: myArrayY_voltage_3[i], });
arry_current_1.push({ x: myArrayX_kwh[i], y: myArrayY_current_1[i], });
arry_current_2.push({ x: myArrayX_kwh[i], y: myArrayY_current_2[i], });
arry_current_3.push({ x: myArrayX_kwh[i], y: myArrayY_current_3[i], });
}
then i have initialized and written the code for my charts
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container1',
type: 'column',
zoomType: 'xy',
resetZoomButton: {
position: {
align: 'right', // by default
verticalAlign: 'top', // by default
x: -250,
y: 5,
//height: 25
},
relativeTo: 'chart'
}
},
title: {
text: 'Energy vs Date & Time',
style: {
//color: '#FF00FF',
fontWeight: 'bold',
//fontSize: '12px'
//sfont: 'bold 200px Verdana, sans-serif',
}
},
xAxis: {
// categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
type: 'datetime',
// max: new Date().getTime(),
//labels: {
// // format: {value:}
// style: {
// fontSize: '13px',
// fontFamily: 'Verdana, sans-serif'
// }
//}
}, yAxis: {
title: {
text: 'Energy (kWh)',
style: {
//color: '#FF00FF',
fontSize: '12px',
//sfont: 'bold 200px Verdana, sans-serif',
}
}
},
as i am displaying 4 charts so i have done the same as like above with other 3 here the things are working good all the data from DB is showing in charts and if DB is updated then on page refresh it is showed but as i wrote above i don't want to refresh the page
for this i have done
var dt = JSON.stringify({
"arryKwh": arry_kwh,
"arryPower": arry_power,
"arryVoltage_1": arry_voltage_1,
"arryVoltage_2": arry_voltage_2,
"arryVoltage_3": arry_voltage_3,
"arryCurrent_1": arry_current_1,
"arryCurrent_2": arry_current_2,
"arryCurrent_3": arry_current_3
});
after that i have done an ajax call and passed data into success alert to view whether it's having my data or not
(function poll() {
setTimeout(function () {
$.ajax({
type: "POST",
url: "/Home/MultiGraph/",
data:dt,
success: function (data)
{
alert(data)
},
});
poll();
}, 5000);
})();
But when i run the application the alert message display with this
I am missing something but what it is i don't know
I have found SignalR but i think it would be time taking as i have to write all things again
Another solution came to mind is that may be if i set a condition in view or controller in which it checks if the DB is updated than it automatically refresh the page
I am confused any help will be appreciated

Plotly.js hover change color of element

I'm working with plotly.js to make a simple world map with some lines on it. The data is simply a csv of latitudes and longitudes, count is nothing important.
Plotly.d3.csv('edgel_latlon.csv', function(err, rows){
function unpack(rows, key) {
return rows.map(function(row) { return row[key]; });}
function getMaxOfArray(numArray) {
return Math.max.apply(null, numArray);
}
var data = [];
var count = unpack(rows, 'To');
var startLongitude = unpack(rows, 'lon1');
var endLongitude = unpack(rows, 'lon2');
var startLat = unpack(rows, 'lat1');
var endLat = unpack(rows, 'lat2');
for ( var i = 0 ; i < count.length; i++ ) {
var opacityValue = count[i]/getMaxOfArray(count);
var result = {
type: 'scattergeo',
locationmode: 'world',
lon: [ startLongitude[i] , endLongitude[i] ],
lat: [ startLat[i] , endLat[i] ],
mode: 'lines',
line: {
width: .5,
color: 'red'
},
opacity: 1
};
data.push(result);
};
var layout = {
title: 'Title',
showlegend: false,
geo:{
resolution:1000,
scope: 'world',
projection: {
type: 'mercator'
},
showland: true,
showcountries: true,
landcolor: 'rgb(243,243,243)',
countrycolor: 'rgb(0,0,0)'
}
};
Plotly.plot(myDiv, data, layout, {showLink: false});
});
When I hover over a line on the map I would like the line to change from the color red to blue, but have no idea how to do this with plotly. Either you can't use the standard D3 methods to access the line or I'm missing something obvious. Thanks!

Categories

Resources