Highcharts renders the other graph's data too - javascript

I have one html page where there are two divs. In each div I am loading different jsp files(one.jsp and two.jsp).
home.html:
<script src="resources/js/jquery.js"></script>
<script type="text/javascript" src="resources/js/highcharts.js"></script>
<script type="text/javascript" src="resources/js/exporting.js"></script>
<script type="text/javascript" src="resources/js/export-csv.js"></script>
<script>
function loadGraphs()
{
$('#plotContainer1').load('one.jsp');
$('#plotContainer2').load('two.jsp');
}
</script>
where plotContainer1 and plotContainer2 are two divs. So that I want to load two graphs at a time.
one.jsp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<div id="container1" style="min-width: 350px; height: 350px; margin: 0 auto"></div>
<script type="text/javascript">
var seriesArray;
var chart;
callAjax();
var graphTitle = "";
var chart;
function drawgraph1() {
Highcharts.setOptions({
colors: ['#54CBE5', '#57B442']
});
chart = $('#container1').highcharts({
chart: {
zoomType: 'x'
},
title: {
text: graphTitle
},
xAxis: {
tickInterval: 30,
type: 'datetime',
categories: xAxisCategories
},
yAxis: {
min : 0,
title: {
text: ''
},
plotLines : [ {
value : 0,
width : 1,
color : '#808080'
} ]
},
plotOptions: {
series: {
marker: {
enabled: false
}
}
},
series : seriesArray
});
};
function callAjax() {
$("#container1").empty();
seriesArray = [{
name: 'line1',
data: []
}, {
name: 'line2',
data: []
}];
xAxisCategories = [];
var params = {"param1" : value};
$.getJSON("graph1datafetcher",params, function(data) {
$.each(data, function(key, val) {
var xaxisPoints=data[key];
xAxisCategories.push(Date.parse(key));
for(var i in xaxisPoints) {
seriesArray[i].data.push(xaxisPoints[i]);
}
});
console.log(" JSON: " + JSON.stringify(data));
drawgraph1();
});
}
</script>
</body>
</html>
two.jsp almost contains the same code. Now first two.jsp loads as it contains less data compared to one.jsp. When one.jsp loads in and shows up in div, the one.jsp graph shows two.jsp data and its own data too. I am logging the data in the console, the data that is coming is fine. So, the problem is somewhere the highchart persists the first data. I have been struggling with this for past 7 hours. Can someone please answer how to resolve this?

Related

Highcharts column chart with data from mongodb

I have tried to create a column chart using highcharts in nodejs and data is getting fetched from mongodb.
I am getting stuck in series option Please help me to get out of it.
The below is my code for ejs file -
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Pie Highcharts Example</title>
<!-- Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="/javascripts/jquery.min.js"></script>
<script type="text/javascript" src="/javascripts/highcharts.js"></script>
<!-- Optional: the exporting module -->
<script type="text/javascript" src="/javascripts/exporting.js"></script>
<!-- Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
chartdata= <%-JSON.stringify(data)%>
var category = [];
var dname=[];
var kdata=[];
for(j=0;j<chartdata.length;j++){
category[j]=[chartdata[j].catname]
// name[j]=[chartdata[j].seriesname]
// data[j]=[chartdata[j].wdata,chartdata[j].hdata,chartdata[j].cdata]
}
for(k=0;k<chartdata.length;k++){
dname[k]=[chartdata[k].seriesname];
}
for(i=0;i<chartdata.length;i++){
kdata[i] = [chartdata[i].wordval,chartdata[i].codeval,chartdata[i].highval];
}
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'column'
},
title: {
text: 'Monthly Average data'
},
xAxis: {
categories: category
},
yAxis: {
min: 0,
title: {
text: 'Rainfall (mm)'
}
},
legend: {
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'right',
verticalAlign: 'top',
x: 0,
y: 40,
floating: true,
shadow: true
},
tooltip: {
formatter: function() {
return ''+
this.series.name +': '+ this.y ;
}
},
plotOptions: {
column: {
pointPadding: 0.3,
borderWidth: 0
}
},
series: [{
name: dname[0],
data: kdata[0]
},
{
name: dname[1],
data: kdata[1]
},
{
name: dname[2],
data: kdata[2]
}
]
});
});
</script>
</head>
<body>
<!-- Add the container -->
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
#NishithChaturvedi - When I am doing this way its working so only the problem with loop I know I am asking silly question but didn't able to rectify.
Thank you for your time I have fixed the problem I was facing in series value
I just created another array var and store the name and data to it and pass that array in series.

Highcharts multiple charts, each with live data

I have the following files:
rsrp.txt, sinr.txt, rssi.txt
each of them containg information like this:
[1433289760000,-83.5]
I want to use multiple charts on the same page.
I tried to use the sample script from the Highcharts page:
var chart; // global
/**
* Request data from the server, add it to the graph and set a timeout to request again
*/
function requestData() {
$.ajax({
url: 'rssi.txt',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 30; // 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, 1700);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'RSSI'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 2.5,
maxPadding: 2.5,
title: {
text: 'dBm',
margin: 80
}
},
series: [{
name: 'RSSI',
data: []
}]
});
});
Copy pasting the script outside the and changing the URL does not work. (only one chart is getting updates)
If I create a second requestData()-function and copy the $(document).ready part does not work either.
Is this possible in Highcharts?
It would be not a problem to combine the input files into a single file, if that would help.
Edit:
I tried to solve it using the answers here:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Signal</title>
<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="highcharts.js"></script>
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script>
var chart; // global
var chartRsrp;
/**
* Request data from the server, add it to the graph and set a timeout to request again
*/
function requestData() {
$.ajax({
url: 'rssi.txt',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 30; // 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, 1700);
},
cache: false
});
}
function requestData2() {
$.ajax({
url: 'rsrp.txt',
success: function(point) {
var series = chartRsrp.series[0],
shift = series.data.length > 30; // shift if the series is longer than 20
// add the point
chartRsrp.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1700);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'RSSI'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 2.5,
maxPadding: 2.5,
title: {
text: 'dBm',
margin: 80
}
},
series: [{
name: 'RSSI',
data: []
}]
});
chartRsrp = new Highcharts.Chart({
chart: {
renderTo: 'container2',
defaultSeriesType: 'spline',
events: {
load: requestData2
}
},
title: {
text: 'RSRP'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 2.5,
maxPadding: 2.5,
title: {
text: 'dBm',
margin: 80
}
},
series: [{
name: 'RSRP',
data: []
}]
});
});
</script>
</head>
<body>
<!-- 3. Add the container -->
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
<div id="container2" style="width: 800px; height: 400px; margin: 0 auto"></div>
Edit 2: solved it that way:
requestData2();
requestData3();
requestData4();
setTimeout(requestData, 1300);
in the first requestData()
In Highcharts-land, each chart needs to be its own object. It's certainly possible to have multiple charts on the same page, but you'd have to make sure that:
Each chart is instantiated separately (in this case, if you're just copying/pasting the $(document).ready part, you're probably stepping on your chart variable. So, instead of a single chart variable you could set these up separately (e.g. chartRsrp = new Highcharts.Chart(...)) and be sure to reference them differently in your requestData calls.
Each chart is rendered to a different DOM element. So, you might render to "container-rsrp", "container-sinr", "container-rssi" etc.
Hopefully this helps!
First of all, each chart have to be instantiated separately, so in your HTML you must have a div with an ID for each chart where the chart will be rendered, for example:
<div id='chartrsrp' class="large-12 columns"></div>
<div id='chartsinr' class="large-12 columns"></div>
<div id='chartrssi' class="large-12 columns"></div>
Next, to render your chart from Js you have to get the div object and instantiate each chart like:
var chartrsrp = $("#chartrsrp");
chartrsrp.highcharts({
title: {
...
},
chart: {
...
});
Hopefully this helps!

Highcharts Won't load from php json, but it could load from data.json file

I tried to make a highchart from JSON data. I make a php file that generating the json and insert the address to the getJSON() like this.
$(document).ready(function() {
$.getJSON("data.php", function(json) {
chart = new Highcharts.Chart({
chart: {...
and it wont work, so i decided to put the php inside the highcharts file like this.
<?php
$mysqli = new mysqli("localhost", "root", "", "test");
$resu = array();
$measurement = $_POST["choosenmeasurement"];
for($i = 0; $i < count($_POST["choosenbusid"]); $i++)
{
$busid = $_POST["choosenbusid"][$i];
$clusid = $_POST["choosenclusterid"][$i];
$fieldname = ''.$measurement.'_BUSID_'.$busid.'_CLUSTERID_'.$clusid;
$sql= "SELECT unix_timestamp, $measurement as $fieldname FROM `get` WHERE bus_id = $busid and cluster_id = $clusid";
$sth = $mysqli->query($sql);
$out = array();
$out['name'] = $fieldname;
while ($rr = $sth->fetch_assoc()) {
$out['data'][] = $rr[$fieldname];
}
array_push($resu,$out);
}
$jsonresult = json_encode($resu);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
$.getJSON(<?php $jsonresult>, function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'testchart',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
yAxis: {
title: {
text: ''
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: json
});
});
});
});
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
and it won't load either and i tried many ways with that method like put $jsonresult into javascript variable, echoing the json, print the json, print/echo into the getJSON() and still wont work eventhough if i echo the json to a blank space it'll print a json structure that i want.
BUT
if i put the JSON file into getJSON() like this
$(document).ready(function() {
$.getJSON("test.json", function(json)
it will works. but i would not copy paste the json that generated into the json file everytime i would load the charts.
i just wondering why. Any help?
I'm doing the same so in javascript part you have to inclide this:
var json = "<?php echo $pepito; ?>";
datar = JSON.parse(json);
This way you have the data from php in javascript
Also it's important to pass data in array and time in timestamp format multiplied by 1000. for example:
$timestamp=strtotime($fila[0].$fila[1])*1000;
//echo "\n".$timestamp;
$hola[0][]=array( $timestamp, (float)$fila[2]);//RGD
$hola[1][]=array( $timestamp, (float)$fila[3]);//RGA
You have to include the libraries before your script, not sure it's important but you should change it just in case:
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
If you have any other quiestion or you need more info let me know.

Ajax dynamic data with column bar chart

Is it possible to run the highcharts column bar charts? I've tried it a couple of times and unfortunately this no real way to refresh the data without reloading it.
I whipped up some pseudo code which is the way I did it at work (I'm not there now so can't get to the code).
Should I whip up a loop and run it like 5,000 times or something with a 5 second delay? I'm not real sure how to proceed.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
< your typical ajax call function here
return some value;
>
$(function () {
<var ajax_far = ajax_function();>
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Monthly Average Rainfall'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
categories: [
'Some Bar'
]
},
yAxis: {
min: 0,
title: {
text: 'Rainfall (mm)'
}
},
legend: {
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true,
shadow: true
},
tooltip: {
formatter: function() {
return ''+
this.x +': '+ this.y +' mm';
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Tokyo',
data: [ajax_var]
}]
});
});
}, 5000);
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
put your ajax code in one function that it call from ready function...try this
$(document).ready(function(){
example();
setInterval("example()",5000);
}
function example()
{
//ajax code here
}
The ajax call should simply obtain new data for the chart to display. There is no need to redraw the entire chart, you can just replace the series data, or add indivual points. Here is a good article on doing this on the highcharts website here http://docs.highcharts.com/#preprocessing-live-data, but the ajax code they suggest is:
/**
* Request data from the server, add it to the graph and set a timeout to request again.
*/
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // Shift if the series is longer than 2.
// Add the point.
chart.series[0].addPoint(point, true, shift);
// Call it again after one second.
setTimeout(requestData, 1000);
},
cache: false
});
}
In this code, the requestData function is called every second (via setTimout). It obtains a new data point via an ajax call to live-server-data.php and uses chart.series[0].addPoint to add it to the chart.
If the ajax call returned the entire series, you would call chart.series[0].setData to replace the entiire series.
The only thing you need to worry about is making sure the chart is created before you start call addPoint or setData.
$(function () {
var chart;
var list;
$(document).ready(function() {
var options = {
chart: {
//all chart attr here
}
//other attr
}
chart = new Highcharts.Chart(options);
setInterval(function() {
$.ajax({
type: "GET",
url: "service",
dataType: "json",
success: function (data)
{
chart.series[0].setData(data);
}
}),1000); //will set ur data to ajax data every 1 sec
if u want to update to existing chart data try addPoint()
});
});

fetching data from mysql databases

Hello everyone is there any possibly to fetch data from mysql databases in javascript . For example i have the following code
<!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 type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="../js/highcharts.js"></script>
<!-- 1a) Optional: add a theme file -->
<!--
<script type="text/javascript" src="../js/themes/gray.js"></script>
-->
<!-- 1b) Optional: the exporting module -->
<script type="text/javascript" src="../js/modules/exporting.js"></script>
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 500);
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
}]
});
});
</script>
</head>
<body>
from this code
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
instead of random no i want to fetch from the database . please guide
You can't connect to a MySQL database from traditional Javascript. You'll have to do that server-side, such as in PHP.
There are some in-between solutions, such as Jaxer, (A tutorial here.), but this would probably be a bit over your head.
No, there's (fortunately) no express-way from JavaScript to MySQL. You'd have to make requests against some custom HTTP-based service (written in whatever programming language) that then accesses MySQL.
Make an AJAX request to the PHP script (using jQuery or whichever way you prefer), and get the PHP script to give you back JSON data of the row using json_encode

Categories

Resources