How to manipulate JSON data in html within a jQuery? - javascript

I have my json file looks like this
{"level" :[
{"color" : "#FF6600", "Polygon" : [
{"lon" : 125.8575930951375,"latt": 36.95626849495004},
{"lon" : 125.8851548404469,"latt": 36.99677151742446},
{"lon" : 125.9128154107602,"latt": 37.03743133552931},
{"lon" : 125.9564137105485,"latt": 37.07788492352393},]},
{"color" : "#FFFF00", "Polygon" : [
{"lon" : 125.8575930951375,"latt": 36.95626849495004},
{"lon" : 125.8851548404469,"latt": 36.99677151742446},
{"lon" : 125.9128154107602,"latt": 37.03743133552931},
{"lon" : 125.9564137105485,"latt": 37.07788492352393},]},
]}
if i declare a variable for the above json format inside my html, then I manage to manipulate the data with the following code
var dataObj = {"level" :[
{"color" : "#FF6600", "Polygon" : [
{"lon" : 125.8575930951375,"latt": 36.95626849495004},
{"lon" : 125.8851548404469,"latt": 36.99677151742446},
{"lon" : 125.9128154107602,"latt": 37.03743133552931},
{"lon" : 125.9564137105485,"latt": 37.07788492352393},]},
{"color" : "#FFFF00", "Polygon" : [
{"lon" : 125.8575930951375,"latt": 36.95626849495004},
{"lon" : 125.8851548404469,"latt": 36.99677151742446},
{"lon" : 125.9128154107602,"latt": 37.03743133552931},
{"lon" : 125.9564137105485,"latt": 37.07788492352393},]},
]}
function UseJSON(){
for (i = 0; i < dataObj.level.length; i++)
{
var polygon = [];
for (j = 0; j < dataObj.level[i].Polygon.length; j++)
{
var point = map.getTransformXY(dataObj.level[i].Polygon[j].lon, dataObj.level[i].Polygon[j].latt,"EPSG:4326","EPSG:900913");
polygon.push(new OpenLayers.Geometry.Point(point.x, point.y));
}
var style_polygon = {strokeColor: "#000000", strokeOpacity: 0.7, fillColor: dataObj.level[i].color, fillOpacity: 0.5, strokeWidth: 1};
var intensityPolygon = new vworld.Polygon(polygon, style_polygon);
map.vectorLayer.addFeatures([intensityPolygon]);
}
}
Refer to this previous answer in SO: How to use json in html
I try to modify my code as per below:
function UseJSON(){
$.getJSON('data.json', function(dataObj) {
for (i = 0; i < dataObj.level.length; i++)
{
var polygon = [];
for (j = 0; j < dataObj.level[i].Polygon.length; j++)
{
var point = map.getTransformXY(dataObj.level[i].Polygon[j].lon, dataObj.level[i].Polygon[j].latt,"EPSG:4326","EPSG:900913");
polygon.push(new OpenLayers.Geometry.Point(point.x, point.y));
}
var style_polygon = {strokeColor: "#000000", strokeOpacity: 0.7, fillColor: dataObj.level[i].color, fillOpacity: 0.5, strokeWidth: 0.5};
var intensityPolygon = new vworld.Polygon(polygon, style_polygon);
map.vectorLayer.addFeatures([intensityPolygon]);
}
});
}
But it does not seems to work. As it seems does not get the data.json file from local. Any idea?
Thank you

Related

Get javascript values from result of php script

I have pie chart webpage (index.html) which is currently getting values from a static .js file.
The original content of the .js file for the pie chart is this:
$( document ).ready(function() {
var ctx110 = document.getElementById("chart110").getContext("2d");
var data110 = [
{
"value": 40,
"color": "#F25656",
"highlight": "#FD7A7A",
"label": "Critical"
},
{
"value": 63.2452,
"color": "#22BAA0",
"highlight": "#36E7C8",
"label": "Other"
},
{
"value": 0,
"color": "#F2CA4C",
"highlight": "#FBDB6E",
"label": "Warning"
}
];
var chart110 = new Chart(ctx110).Pie(data110,{
segmentShowStroke : true,
segmentStrokeColor : "#fff",
segmentStrokeWidth : 2,
animationSteps : 100,
animationEasing : "easeOutBounce",
animateRotate : true,
animateScale : false,
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>",
responsive: true
});
});
However, I need to make the values in the var data110 variable dynamic.
I have a php script that, when run, spits out the required value and my issue is, I'm having problems getting the pie chart to load after I incorporate the php script into the above code.
Here's my attempt (I'm completely new to web development, so please forgive my ineptitude here - i know it's very ugly):
$( document ).ready(function() {
var ctx110 = document.getElementById("chart110").getContext("2d");
function internal_loadXMLDoc1() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("myDivAX1").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","getnum.php?os-metrics",true);
xmlhttp.send();
}
var dskmetric = internal_loadXMLDoc1();
var data110 = [
{
"value": dskmetric,
"color": "#F25656",
"highlight": "#FD7A7A",
"label": "Critical"
},
{
"value": 63.2452,
"color": "#22BAA0",
"highlight": "#36E7C8",
"label": "Other"
},
{
"value": 0,
"color": "#F2CA4C",
"highlight": "#FBDB6E",
"label": "Warning"
}
];
var chart110 = new Chart(ctx110).Pie(data110,{
segmentShowStroke : true,
segmentStrokeColor : "#fff",
segmentStrokeWidth : 2,
animationSteps : 100,
animationEasing : "easeOutBounce",
animateRotate : true,
animateScale : false,
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>",
responsive: true
});
});
EDIT (based on #AL-zami advice):
$( document ).ready(function() {
var ctx110 = document.getElementById("chart110").getContext("2d");
function internal_loadXMLDoc1() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// Do your work here
var data110 = [
{
**"value": [this needs to be dynamic]**,
"color": "#F25656",
"highlight": "#FD7A7A",
"label": "Critical"
},
{
**"value": [this needs to be dynamic]**,
"color": "#22BAA0",
"highlight": "#36E7C8",
"label": "Other"
},
{
"value": 0,
"color": "#F2CA4C",
"highlight": "#FBDB6E",
"label": "Warning"
}
];
var chart110 = new Chart(ctx110).Pie(data110,{
segmentShowStroke : true,
segmentStrokeColor : "#fff",
segmentStrokeWidth : 2,
animationSteps : 100,
animationEasing : "easeOutBounce",
animateRotate : true,
animateScale : false,
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>",
responsive: true
});
}
}
xmlhttp.open("POST","getnum.php?os-metrics",true);
xmlhttp.send();
}
internal_loadXMLDoc1();
});
Here's the PHP script getnum.php:
<?php
$allargs = $_SERVER["argv"];
$argscou = $_SERVER["argc"];
if ( $argscou == 0 ) {
die();
} else {
$upatterns = var_export($allargs, true) ;
if (strpos($upatterns, '__') !== false) {
$type_val = explode("__", $allargs[0]);
} else {
$type_val = $allargs;
}
$compon1 = $type_val[0];
if ($compon1== "30day-expirations") {
$compon2 = $type_val[1];
echo '<p class="counter">' . "$compon2" . '</p>'. "\n";
} else if ( ($compon1 == "getnum.php") || ($compon1 == "os-disk-usage") ) {
$duvalue = "400";
echo "$duvalue";
file_put_contents('4filename.txt', $duvalue, FILE_APPEND);
}
}
?>
Your problem statement is not clear. Hard to determine what you are trying to accomplish. If I understand you correctly, your problem lies in you post request handler. XMLHttpRequest is a asynchronous request. Your rest of the code run to completion before the post request is resolved.
var dskmetric = internal_loadXMLDoc1();
The above statement doesn't return anything. Try to run you chart generation code inside the handler function.
var ctx110 = document.getElementById("chart110").getContext("2d");
function internal_loadXMLDoc1() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// Do your work here
}
}
xmlhttp.open("POST","getnum.php?os-metrics",true);
xmlhttp.send();
}
internal_loadXMLDoc1();
If you are not submitting any form try to change the request method to GET
You can use the following example:
<?php
$data = [
[
"value" => 'dskmetric',
"color" => "#F25656",
"highlight" => "#FD7A7A",
"label" => "Critical"
],
[
"value" => 63.2452,
"color" => "#22BAA0",
"highlight" => "#36E7C8",
"label" => "Other"
],
[
"value" => 0,
"color" => "#F2CA4C",
"highlight" => "#FBDB6E",
"label" => "Warning"
]
];
?>
<script type="application/json" id="j-data">
{ "data": <?php echo json_encode($data ?? []); ?>}
</script>
<script>
var data = JSON.parse($("#j-data")[0].innerHTML);
</script>

appcelerator : webview to show graph using HighCharts

I am developing an application which sends data to a webview and it uses highcharts to draw graph . The problem I am facing is I am using same graph to display different data series , so when I am calling the graph for 10th time , it firsts shows the y axis labels of all the previous 9 graphs , then the graph is loaded with labels of 10th graph . Any help .
<html>
<head>
<script src="./jquery.min.jsl"></script>
<script src="./highcharts.jsl"></script>
<script src="./exporting.jsl"></script>
<meta name="viewport" content="user-scalable=no">
<script>
function renderGraph(graphdata) {
var graphObj = JSON.parse(graphdata);
var chart = null;
Highcharts.setOptions({
lang : {
numericSymbols : ["K", "M", "G", "T", "P", "E"]
}
});
var change = {
0 : '$0K',
2 : '$2K',
4 : '$4K',
6 : '$6K',
8 : '$8K'
};
var xAxisLegends = graphObj.bottomLegends;
var seriesData = graphObj.seriesData;
var xAxisLegends = graphObj.bottomLegends;
//['Q2, 16', 'Q3, 16', 'Q4, 16', 'Q1, 17'];
var columnColors = ["#69C3DB", "#3a8a9f"];
var seriesData = graphObj.seriesData;
/*[{
name : 'Budget',
showInLegend : false,
data : [2, 4, 6, 8]
}, {
name : 'Utilisation',
showInLegend : false,
data : [1, 2, 3, 4]
}];*/
// variables which have diff values according to OS
var chartProperties = {};
// properties to assign to Charts's object
var graphHeight = 0;
// height of chart
var graphWidth = 0;
//Width of the column
var pointWidth;
// Separating the graph dimensions & styling properties as per OS name & version
if (graphObj.osname == "iphone") {
chartProperties = {
type : 'column',
renderTo : 'container'
};
xAxisProp = {
gridLineWidth : 0,
categories : xAxisLegends,
crosshair : true
};
yAxisProp = {
min : 0,
gridLineWidth : 0,
tickAmount : 5,
title : {
text : ' '
},
labels : {
formatter : function() {
var value = this.axis.defaultLabelFormatter.call(this);
return '$' + value;
}
}
};
pointWidth = 5;
} else if (graphObj.osname == "android") {
chartProperties = {
type : 'column',
plotBackgroundColor : null,
plotBackgroundImage : null,
plotBorderWidth : 0,
plotShadow : false,
height : 450,
marginTop : 100,
marginLeft : 120
},
xAxisProp = {
categories : xAxisLegends,
width : 800,
tickmarkPlacement : 'on',
labels : {
y : 40,
style : {
color : '#333333',
fontSize : '25',
fontFamily : 'Metropolis-Light',
opacity : '.6'
},
}
};
yAxisProp = {
gridLineWidth : 0,
min : 0,
tickAmount : 5,
offset : 60,
title : {
text : ''
},
labels : {
align : 'left',
style : {
color : '#333333',
fontSize : '28',
fontFamily : 'Metropolis-Light',
opacity : '.5'
},
formatter : function() {
var value = this.axis.defaultLabelFormatter.call(this);
return '$' + value;
}
},
};
pointWidth = 10;
if (parseInt(graphObj.osversion) >= 500 && parseInt(graphObj.osversion) <= 600) {
graphHeight = 600;
} else {
graphHeight = 630;
}
}
chart =
Highcharts.chart('container', {
chart : chartProperties,
credits : {
enabled : false
},
tooltip : {
enabled : false
},
exporting : {
enabled : false
},
title : {
text : ''
},
xAxis : xAxisProp,
yAxis : yAxisProp,
plotOptions : {
column : {
pointPadding : 0.2,
borderWidth : 0,
groupPadding : 0.38,
pointWidth : pointWidth
}
},
colors : columnColors,
series : seriesData
});
}
</script>
</head>
<body>
<div id="container" style="height: 100%; width: 100%; position : center;"></div>
</body>
Here is the function inside the controller which calls the graph using evalJS.
$.webViewPerformanceGraph.url = "/html/Performance.html";
$.webViewPerformanceGraph.addEventListener('load', function() {
$.webViewPerformanceGraph.evalJS("renderGraph('" + JSON.stringify(params) + "');");

Using Different Colors In a Chart

My Code:
<div><canvas id="canvas_line" height="200" width="800"></canvas></div>
<div><canvas id="canvas_bar" height="200" width="800"></canvas></div>
<script>
var lineChartData = {
labels : ["14:00","15:00","16:00","17:00","18:00","19:00","20:00","22:00"],
datasets : [
{
label: "CPU IDLE",
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 : [85,35,65,59,90,81,56,55,40,100]
}
]
}
var barChartData = {
labels : ["12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00","22:00"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
data : [85,35,65,59,90,81,56,55,40,100]
}
]
}
var ctx_line = document.getElementById("canvas_line").getContext("2d");
window.myLine = new Chart(ctx_line).Line(lineChartData, {
responsive: true
});
var ctx_bar = document.getElementById("canvas_bar").getContext("2d");
window.myLine = new Chart(ctx_bar).Bar(barCharData, {
responsive: true
});
</script>
It looks like this, everything is grey.
But I'd like to change the lineChart's pointColor and barChart's fillcolor to red if its data is above 80, the data below 80 are still grey.
I want it like this, but I don't know how to use different colors in a canvas.
<!DOCTYPE html>
<html>
<head>
<title>123</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://apps.bdimg.com/libs/Chart.js/0.2.0/Chart.min.js"></script>
</head>
<body>
<canvas id="chartCanvas" height="200" width="800"></canvas>
<script>
$(document).ready(function() {
var chartData = {
labels: ["12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00","22:00"],
datasets: [
{
data : [85,35,65,59,90,81,56,55,40,100],
fillColor: 'rgba(220,220,220,0.2)',
strokeColor: 'rgba(220,220,220,1)'
}
]
}
var chartCanvas = document.getElementById("chartCanvas").getContext("2d");
var barChart = new Chart(chartCanvas).Bar(chartData, {responsive: true});
// Set warning color
var bars = barChart.datasets[0].bars;
for(var i = 0; i < bars.length ; i++) {
if(bars[i].value > 80) {
bars[i].fillColor = "rgba(255, 0, 0, 0.2)";
bars[i].strokeColor = "rgba(220, 0, 0, 0.5)";
}
}
// Update the chart
barChart.update();
});
</script>
</body>
</html>
You have to loop to all the bars/points of your chart, check if the value is over 80 and set the color.
Here is an example for the bar chart:
var bars = barChart.datasets[0].bars;
for(var i = 0; i < bars.length; i++) {
if(bars[i].value > 80) {
bars[i].fillColor = "rgba(255, 0, 0, 0.2)";
bars[i].strokeColor = "rgba(220, 0, 0, 0.5)";
}
}
// Update the chart
barChart.update();
Check out this fiddle for a working demo.
To set the color on a line chart you just have to iterate over the points instead of the bars:
var points = lineChart.datasets[0].points;
And of course set the pointColor or whatever you want.

How to sort y-axis by different data rows with dimple.js

This is a follow-up of this topic. I'm trying to dynamically sort the y-axis by different data rows. My data structure:
var dataGraph = [];
for (var i = 0; i < data.length; i++) {
//data[i].eusiInd = (data[i].eusiInd === 99) ? '' : data[i].eusiInd;
dataGraph.push(
{'Index' : 'Eusi-Index', 'Country' : data[i].ctry, 'Year' : data[i].year, 'Disaggregation' : data[i].disagg, 'Index Value' : data[i].eusiInd, 'Identifier' : 'Eusi-Index, '+data[i].disagg},
{'Index' : 'Standard of Living', 'Country' : data[i].ctry, 'Year' : data[i].year, 'Disaggregation' : data[i].disagg, 'Index Value' : data[i].stdLiving, 'Identifier' : 'Standard of Living, '+data[i].disagg},
{'Index' : 'Housing', 'Country' : data[i].ctry, 'Year' : data[i].year, 'Disaggregation' : data[i].disagg, 'Index Value' : data[i].housing, 'Identifier' : 'Housing, '+data[i].disagg},
{'Index' : 'Health', 'Country' : data[i].ctry, 'Year' : data[i].year, 'Disaggregation' : data[i].disagg, 'Index Value' : data[i].health, 'Identifier' : 'Health, '+data[i].disagg},
{'Index' : 'Social Relations', 'Country' : data[i].ctry, 'Year' : data[i].year, 'Disaggregation' : data[i].disagg, 'Index Value' : data[i].socRel, 'Identifier' : 'Social Relations, '+data[i].disagg},
{'Index' : 'Work', 'Country' : data[i].ctry, 'Year' : data[i].year, 'Disaggregation' : data[i].disagg, 'Index Value' : data[i].work, 'Identifier' : 'Work, '+data[i].disagg}
);
}
// Remove missing values
dataGraph = dataGraph.filter(function (element) {
return (Math.floor(element['Index Value']) !== 99);
});
// Data for one year
var dataGraphFiltered = dimple.filterData(dataGraph, 'Year', '2010');
I created a mixed bars/bubbles/lines chart and want to be able to dynamically sort the y-axis. My code looks like this:
var barData = [],
lineData = [],
keyIndex = "Eusi-Index";
for (var i = 0; i < dataGraphFiltered.length; i++) {
if (dataGraphFiltered[i]['Index'] === keyIndex) {
barData.push(dataGraphFiltered[i]);
} else {
lineData.push(dataGraphFiltered[i]);
}
}
var svg = dimple.newSvg("#graphic", 550, 700);
var chart = new dimple.chart(svg),
bars,
lines,
dots;
chart.setBounds(50, 30, 480, 630);
var xAxis = chart.addMeasureAxis('x', 'Index Value');
xAxis.overrideMax = 1;
var yAxis = chart.addCategoryAxis('y', 'Country');
bars = chart.addSeries('Identifier', dimple.plot.bar);
bars.data = barData;
bars.getTooltipText = function (e) {
return [
'Country: '+e['cy'],
e['aggField'][0],
'Index Value: '+Math.round10(e['xValue'],-3)
];
};
chart.assignColor('Eusi-Index, total', '#D3D3D3', '#D3D3D3');
lines = chart.addSeries('Identifier', dimple.plot.line);
lines.data = lineData;
dots = chart.addSeries('Identifier', dimple.plot.bubble);
dots.data = lineData;
dots.getTooltipText = function (e) {
return [
'Country: '+e['cy'],
e['aggField'][0],
'Index Value: '+Math.round10(e['xValue'],-3)
];
};
yAxis.addOrderRule('Index Value', false);
chart.draw();
I probably need to use a sort function with "addOrderRule" to be able to sort by every "Identifier" data row displayed in the chart but I couldn't find out how to accomplish that. I'd be very grateful for suggestions.
I could solve the sorting issue myself by using:
yAxis.addOrderRule(function(a,b){
var avalue, bvalue;
for (var i=0; i<a['Identifier'].length; i++) {
avalue = 0;
if (a['Identifier'][i] === 'Housing, total') {
avalue = a['Index Value'][i*2];
break;
}
}
for (var i=0; i<b['Identifier'].length; i++) {
bvalue = 0;
if (b['Identifier'][i] === 'Housing, total') {
bvalue = b['Index Value'][i*2];
break;
}
}
return avalue-bvalue;
}, false);
By changing 'Housing, total' I can decide by which Identifier to sort my y-axis

How do I use a string variable in an object?

I have a string, that looks like this if I log it in the console:
0.0196078431373,0.078431372549,0.0196078431373,0.0392156862745,0.0196078431373,0.0196078431373,0.0196078431373,0.0588235294118,0.0588235294118
I try to use it in an object for a chart, like this:
var barChartData = {
labels : ["People (2.5%)","War (2.1%)","Sharing (0.8%)","Animals (1.4%)","Friends (0.3%)"],
datasets : [
{
fillColor : "rgba(74,219,168,0.8)",
strokeColor : "rgba(56,193,145,1)",
data : [strTags]
}
]
}
But the strTags isn't printed (the numbers), it shows like above. How can I fix this that it shows like this:
var barChartData = {
labels : ["People (2.5%)","War (2.1%)","Sharing (0.8%)","Animals (1.4%)","Friends (0.3%)"],
datasets : [
{
fillColor : "rgba(74,219,168,0.8)",
strokeColor : "rgba(56,193,145,1)",
data : [0.0196078431373,0.078431372549,0.0196078431373,0.0392156862745,0.0196078431373,0.0196078431373,0.0196078431373,0.0588235294118,0.0588235294118]
}
]
}
You need to convert the String to an array first, e.g., by using split():
var barChartData = {
labels : ["People (2.5%)","War (2.1%)","Sharing (0.8%)","Animals (1.4%)","Friends (0.3%)"],
datasets : [
{
fillColor : "rgba(74,219,168,0.8)",
strokeColor : "rgba(56,193,145,1)",
data : strTags.split(',')
}
]
}
If you need it to be an array of numbers then you have to parse the string to a floating point number. You can do this:
var barChartData = {
labels : ["People (2.5%)","War (2.1%)","Sharing (0.8%)","Animals (1.4%)","Friends (0.3%)"],
datasets : [
{
fillColor : "rgba(74,219,168,0.8)",
strokeColor : "rgba(56,193,145,1)",
data : strTags.split(',').map(function(element, index, array) {
return parseFloat(element);
})
}
]
}
Another solution is JSON.parse
var barChartData = {
labels : ["People (2.5%)","War (2.1%)","Sharing (0.8%)","Animals (1.4%)","Friends (0.3%)"],
datasets : [
{
fillColor : "rgba(74,219,168,0.8)",
strokeColor : "rgba(56,193,145,1)",
data : JSON.parse("["+ strTags + "]");
}
]
}

Categories

Resources