I want to create a graph using Highcharts plugin and the data should be parsed as an XML file.
The XML file data2.xml is,
<data>
<row><t>1347559200</t><v>2.1600000000e+01</v></row>
<row><t>1347562800</t><v>2.1504694630e+01</v></row>
<row><t>1347566400</t><v>2.1278633024e+01</v></row>
</data>
The HTML coding is,
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>line chart</title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="highcharts.js"></script>
<script src="exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
<script type="text/javascript">
$(document).ready(function(){
options = {
chart: {
renderTo: 'container',
type: 'spline'
},
title: {
text: 'Temperatures'
},
subtitle: {
text: 'An example of time data in Highcharts JS'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
}
},
yAxis: {
title: {
text: 'T (°C)'
},
min: 0
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%e. %b', this.x) +': '+ this.y +' m';
}
},
series: [{
name: 'Temperature',
data: []
}]
}
$.ajax({
type: "GET",
url: "data2.xml",
dataType: "xml",
success: function(xml) {
var series = { data: []
};
$(xml).find("row").each(function()
{
var t = parseInt($(this).find("t").text())*1000
var v = parseFloat($(this).find("v").text())
series.data.push([t,v]);
});
options.series.push(series);
}
});
chart = new Highcharts.Chart(options);
});
</script>
</body>
</html>
If I execute this code It opens fine in Internet Explorer and displays the result as
When I open this file in Chrome it gives me the result as,
with the error message:
XMLHttpRequest cannot load file:///C:/data2.xml. Origin null is not allowed by Access- Control-Allow-Origin.
so that I used Tomcat server to run this. Though it displays the same chart image without the mentioned error message.
How to overcome this?? How can I display the chart in Google Chrome by fetching data from xml file by solving this issue??
This is caused by a security restriction in Chrome to stop malicious web pages from accessing your local files. See more about this at http://en.wikipedia.org/wiki/Same_origin_policy
You can disable it temporarily by running chrome from the command/dos prompt with the switch --disable-web-security
e.g. chrome.exe --disable-web-security
alternatively try running the page from a local web server. Apache and nginx are available for free if you don't have access to IIS
I got this working out..
I just run this code by using Apache/Tomcat..
I think the error I have made is that
1. I have to save this file in .jsp format.
2. add var to chart and options variable.
3. Use this chart = new Highcharts.Chart(options); inside the success function.
Related
Scenario :
A json file
Read json data and plot graph using highcharts
Problem: Getting can't convert undefined to object when loading html without breakpoint in mozilla firefox.
When loading with a breakpoint the graph is getting perfectly plotted.
without breakpoint, getting myjson as undefined in function chartFormyJson
Code :
I have a node project and I am starting http server using npm run serve.
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="scriptFile.js"></script>
</head>
<body>
<div id="container" style="width:100%; height:400px;"></div>
</body>
</html>
scriptFile.js
var myjson;
fetch('./data.json').then(response => response.json()).then(data => {
myjson=data["myjson"];
})
if( document.readyState !== 'loading' ) {
console.log( 'document is already ready, just execute code here' );
chartFormyJson();
} else {
document.addEventListener('DOMContentLoaded', function () {
console.log( 'document was not ready, place code here' );
chartFormyJson();
});
}
function chartFormyJson(){
var myChart = Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Plot bar graph per year'
},
yAxis: {
title: {
text: 'Count'
}
},
xAxis: {
categories: Object.keys(myjson)
},
series: [{
data: Object.values(myjson)
}]
});
}
Need guidance in why it happening this way.Seems something related with loading of data/variables/order of call to js from html.But I am not an expert on these so will really appreciate any help on this.
Let me know if any further info is needed.
Data loaded from local csv file. Webpage run on local Node 'Connect' and 'serveStatic' webserver.
Navigator and the xAxis shows numbers instead of dates stored in the csv file, hence rangeselector and zoom doesn't work.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/data.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>
</head>
<body>
<div id="container" style="width:80%; height:600px;"></div>
</body>
<script>
$(function () {
var myChart = Highcharts.stockChart('container', {
title: {
text: 'Consumption'
},
xAxis: {
type: 'datetime',
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: 'Kilogram'
}
},
navigator: {
xAxis: {
isInternal: true
},
yAxis: {
isInternal: true
}
},
data: {
csvURL: window.location.origin + '/trend.csv'
}
});
});
</script>
</html>
The 'isInternal' parameters are set to workaround this issue.
When I select 'View data table' in the menu the following is displayed:
Date Value
09-06-2018 18:00:15 1296.26098632813
09-06-2018 18:28:09 1451.98901367188
2 563.752014160156
3 429.237213134766
4 445.504516601563
5 1216.92199707031
...
There is something odd going on with the dates. It looks like only the first two rows are processed correctly.
Can anyone please take a look, and maybe point me in the right direction?
Sample from csv file:
DateTime;Value
09/06/2018 18:00:15;1296.26098632813
09/06/2018 18:28:09;1451.98901367188
09/06/2018 18:56:03;563.752014160156
09/06/2018 19:23:57;429.237213134766
The problem comes from your dates being formatted dd/mm/YYYY HH:MM:SS, when javascript expects mm/dd/YYYY HH:MM:SS. If there are just dates, then this can be handled with dateFormat. However, since there is also time involved, it fails. To take care of that we can parse dates manually, like this:
function parseEUdate(d) {
return (new Date(
d.substring(6,10), //Year
d.substring(3,5) - 1, //Month
d.substring(0,2), //Day
d.substring(11,13), //Hour
d.substring(14,16), //Minute
d.substring(17,19) //Second
)).getTime()
}
This is then used in highcharts like this:
data: {
parseDate: function(d) {
return parseEUdate(d)
},
...
}
Working JSFiddle example: https://jsfiddle.net/ewolden/frjp96w8/75/
API on parseDate: https://api.highcharts.com/highstock/data.parseDate
Date() documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
I have a influxdb database and i would like to display its datas into a chart using highchart.
To do so, I'm taking the data from the database with :
https://github.com/vicanso/influxdb-nodejs
var time;
var valeur;
const Influx = require('influxdb-nodejs');
const client = new Influx('http://127.0.0.1:8086/aTimeSeries');
//query last value
client.queryRaw('select * from "valeurs" group by * order by desc limit 1')
.then((data) => {
time = Date.parse(data.results[0].series[0].values[0][0]);
valeur = data.results[0].series[0].values[0][1];
console.info("[" + time + "," + valeur + "]");
}).catch(console.error);
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/json'});
res.write("[" + time + "," + valeur + "]");
res.end();
}).listen(8080);
Then to display it, I try to use the example provide by Highcharts :
https://www.highcharts.com/docs/working-with-data/live-data
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script>
var chart; // global
/**
* Request data from the server, add it to the graph and set a timeout to request again
*/
function requestData() {
$.ajax({
url: 'http://localhost:8080/',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
</script>
</head>
<body>
<!-- 3. Add the container -->
<div id="container" style="width: 100%; height: 100%; margin: 0 auto"></div>
</body>
But as it's working with PHP, I had a lot of little issues, so I tried to switch in nodejs.
[1523957858507,40]
My nodejs file display the right data, the same way as my PHP file was doing it.
What i want is that my index html take the data from localhost:8080 where my JS send a json array.
thanks for your help
I found this, after making my own solution :') . But this one is much easier.
visualizing-influxdb-data-with-highcharts
This is my problem:
I was playing with ECharts JavaScript library, I wanted to retrieve the image data (I know there is a save as image toolbox). When I try to access the function getDataUrl, or getConnectedDataUrl, I get the following error:
"myChart.getDataUrl is not a function"
But when I try to do the same on the browser (or Firebug) console, I get the info I want. When I call get_data() on the console also get the error I mention before. I'm confused.
What am I doing wrong?
There is the example code:
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button type="button" onclick="get_data()">holi</button>
<div id="main" style="width:400px;height:300px;"></div>
<script src="echarts.min.js"></script>
<script type="text/javascript">
// based on prepared DOM, initialize echarts instance
var myChart = echarts.init(document.getElementById('main'));
// specify chart configuration item and data
var option = {
title: {
text: 'Test'
},
tooltip: {},
legend: {
data:['Cosas']
},
xAxis: {
data: ["asdf","qwerty","lol"]
},
yAxis: {},
series: [{
name: 'Cosas',
type: 'bar',
data: [1, 3, 5]
}],
toolbox: {
show : true,
feature : {
mark : {show: false},
saveAsImage : {show: true, title: "save"}
}
}
};
// use configuration item and data specified to show chart
myChart.setOption(option);
function get_data(){
return myChart.getConnectedDataUrl();
};
</script>
</body>
</html>
You just misspelled the function names. They are called getDataURL() and getConnectedDataURL() (with uppercase URL).
I want to present a pie chat, the data came from csv file (excel).
I have html file (index.html) and js file (loadData2.js),
when I print the data in js file I get It like : word,number
donald,8
trump,12
refused ,2
to,7
release ,3
his,6
so I see the data ok.
one field is a word and the other is a number.
I get an error: "Uncaught TypeError: $(...).CanvasJSChart is not a function(…)"
my html code:
<!DOCTYPE html>
<html>
<head>
<title>hw 1</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="includes/loadData2.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="canvas/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
<script>
(function(){
getData2();
})();
</script>
</div>
</body>
</html>
my js code:
function getData2()
{
console.log("hello");
$.get('data/words.csv', function(data) {
console.log(data);
//Better to construct options first and then pass it as a parameter
var options = {
exportEnabled: true,
animationEnabled: true,
title: {
text: "Exporting Chart as Image"
},
data: [
{
type: "splineArea", //change it to line, area, bar, pie, etc
dataPoints: [data]
}
]
};
$("#chartContainer").CanvasJS.Chart(options);
});
}
what I need to do to in order to see my chart on the screen?
Thanks,
You are including CanvasJs, and trying to use its jQuery plugin.
replace <script src="canvas/canvasjs.min.js"></script> by the right file and it'll work.
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/jquery.canvasjs.min.js"></script>
To create a Chart using the regular library would go like this :
var options = {
exportEnabled: true,
animationEnabled: true,
title: {
text: "Exporting Chart as Image"
},
data: [
{
type: "splineArea", //change it to line, area, bar, pie, etc
dataPoints: [data]
}
]
};
var chart = new CanvasJS.Chart("chartContainer",options);
chart.render