How do I update my X axis header title on highcharts? - javascript

I am using Datatables to create Highcharts. Everything functions as intended, however I am not sure how to extract the X axis title from Column 1. (Data1, Data2, Data3, Data4, Data5 etc.). I am not sure what am I missing in my code. Any advice would be appreciated because I don't know much about Javascript. Thanks in advance.
The chart should look like this.
See screenshot below.
Link to code - http://live.datatables.net/muvoyacu/2/edit
$(document).ready(function() {
var table = $("#example_full2").DataTable({
searching:false,
lengthChange: false,
ordering: false,
info: false,
paging: false,
} );
//var salary = getSalaries(table);
var salary = getRow(table,0);
var salary2 = getRow(table, 1);
var salary3 = getRow(table, 2);
var salary4 = getRow(table, 3);
var salary5 = getRow(table, 4);
// Declare axis for the column graph
var axis = {
id: "salary",
min: 0,
title: {
text: "Number"
}
};
// Declare inital series with the values from the getSalaries function
var series = {
name: "2012",
data: Object.values(salary)
};
var series2 = {
name: "2013",
data: Object.values(salary2)
};
var series3 = {
name: "2014",
data: Object.values(salary3)
};
var series4 = {
name: "2015",
data: Object.values(salary4)
};
var series5 = {
name: "2016",
data: Object.values(salary5)
};
var myChart = Highcharts.chart("container", {
chart: {
type: "column"
},
title: {
text: "Test Data"
},
xAxis: {
categories: Object.keys(salary)
},
yAxis: axis,
series: [series, series2, series3, series4, series5]
});
// On draw, get updated salaries and refresh axis and series
table.on("draw", function() {
salary = getSalaries(table);
myChart.axes[0].categories = Object.keys(salary);
myChart.series[0].setData(Object.values(salary));
});
});
function getSalaries(table) {
var salaryCounts = {};
var salary = {};
}
function getRow(table, row) {
var chart = {};
var data = table.row(row).data();
for (i=1; i<data.length; i++) {
var x = $( table.column( i ).header() ).html();
var y = data[i].replace(/[^0-9.]/g, "") * 1;
chart[x] = y;
}
return chart;
}
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<meta charset=utf-8 />
</head>
<body>
<div id="container" style=" width: 100%; height: 400px;"></div>
<div class="container">
<table id="example_full2" class="display nowrap" width="100%"><thead>
<tr><th>Year</th><th>2012</th><th>2013</th><th>2014</th><th>2015</th><th>2016</th><th>2017</th><th>2018</th><th>2019</th><th>2020</th><th>2021</th></tr></thead>
<tr ><td> Data1</td><td>3,823</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
<tr ><td> Data2</td><td>800</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
<tr ><td> Data3</td><td>900</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
<tr ><td> Data4</td><td>200</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
<tr ><td> Data5</td><td>300</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
<tr ><td> Data6</td><td>400</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
</tbody></table>

Related

How to add DOM number function in ajax stocks datatable

I am trying to create a live crypto currency price chart with jQuery, Javascript, Ajax and Websocket. Datatable is using for sorting purpose. Live crypto currency price is always appearing in <input>. It will always work outside of the datatable <table>. But if I put <input> in the datatable <table>, live price is not appearing. I searched in google and found the solution. DOM function needed to getting live number value in datatable <input>. I am using this https://datatables.net/examples/advanced_init/stocks.html datatable for my project. I got DOM javascript code from https://datatables.net/examples/plug-ins/dom_sort.html for live DOM number sorting.
<script type="">
$.fn.dataTable.ext.order['dom-text-numeric'] = function (settings, col) {
return this.api()
.column(col, { order: 'index' })
.nodes()
.map(function (td, i) {
return $('input', td).val() * 1;
});
};
$(document).ready(function () {
$('#example').DataTable({
columns: [
{ orderDataType: 'dom-text-numeric' },
],
});
});
</script>
These are the javascript code for live DOM soring. I don't know how/where put this codes in my Ajax javascript file.
In the ajax javascript fie, I added,
return type === 'display' ?
'<input type="text" id="btc-price" value="">' :
val;
So <input> is appearing in web page without live crypto price. I think DOM is missed in this datatable.
I tried many times. But all my efforts was failure.. Codepen preview: https://codepen.io/themecode/pen/VwxPOpJ Please help me..
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-sparklines/2.1.2/jquery.sparkline.min.js"></script>
</head>
<body>
<!-- **************************************** -->
<table id="example" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Symbol</th>
<th>Price</th>
<th>Chnge</th>
<th>Last</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Symbol</th>
<th>Price</th>
<th>Chnge</th>
<th>Last</th>
</tr>
</tfoot>
</table>
<!-- **************************************** -->
<input type="text" id="btc-price" value="">
<input type="text" id="ltc-price" value="">
<!-- **************************************** -->
<script type="text/javascript">
const streams = {
'btcusdt#trade': { name: 'btc', input: document.getElementById('btc-price') },
'ltcusdt#trade': { name: 'ltc', input: document.getElementById('ltc-price') },
};
const streamParams = Object.entries(streams).map(([streamId]) => streamId).join(`/`);
const streamUrl = `wss://stream.binance.com:9443/stream?streams=${streamParams}`;
const wss = new WebSocket(streamUrl);
wss.onmessage = (event) => {
const eventData = JSON.parse(event.data);
const streamId = eventData.stream;
const latestPrice = Number.parseFloat(eventData.data.p);
const lastPrice = streams[streamId].lastPrice || latestPrice;
// compare latest and last prices
const inputClass = latestPrice > lastPrice
? 'inc'
: latestPrice < lastPrice ?
'dec' : '';
// update relevant input with value
const input = streams[streamId].input;
// remove any existing classes
input.classList.remove('inc','dec');
// add inc/dec class only
if (inputClass)
input.classList.add(inputClass);
// set input value
input.value = latestPrice.toFixed(2);
// save the latest price for this coin.
streams[streamId].lastPrice = latestPrice;
// Call calculators.change() here - I can't actually add it because it will break the snippet.
// calculators.change;
};
</script>
<script type="text/javascript">
$(document).ready(function() {
var stock_data = [
{
"name": "ACME Gadgetsrrrrrrr",
"symbol": "AGDTS",
"last": [2, 9, 14, 18, 23, 27, 39]
},
{
"name": "Spry Media Productions",
"symbol": "SPMP",
"last": [1.12, 1.11, 1.08, 1.08, 1.09, 1.11, 1.08]
},
{
"name": "Widget Emporium",
"symbol": "WDEMP",
"last": [3.40, 3.39, 3.46, 3.51, 3.50, 3.48, 3.49]
},
{
"name": "Sole Goodman",
"symbol": "SGMAN",
"last": [16.20, 16.40, 16.36, 16.35, 16.61, 16.46, 16.19]
},
{
"name": "Stanler Bits and Bobs",
"symbol": "SBIBO",
"last": [82.51, 83.47, 83.40, 83.68, 83.81, 83.29, 83.72]
}
];
let table = $('#example').DataTable({
ajax: function(dataSent, callback, settings) {
let data = this.api().ajax.json();
if(data == undefined) {
data = stock_data; // ======================= data = stock_data;
} else {
data = data.data;
for(i = 0; i < data.length; i++) {
data[i].last.push(data[i].last.shift())
}
}
callback({data: data});
},
paging: false,
initComplete: function() {
let api = this.api();
setInterval(function() {
api.ajax.reload();
}, 3000);
},
drawCallback: function() {
$('.sparkline')
.map(function() {
return $('canvas', this).length ? null : this;
})
.sparkline('html', {
type: 'line',
width: '250px'
})
},
columns: [
// ## 01 // Price
{
data: null, // Price
render: function(data, type, row, meta) {
return row.last[row.last.length - 1].toFixed(2);
}
},
// ## 02 // Difference
{
data: null, // Difference
render: function(data, type, row, meta) {
var val = (row.last[row.last.length - 1] - row.last[row.last.length - 2]).toFixed(2);
var colour = val < 0 ? 'red' : 'green'
return type === 'display' ?
'<input type="text" id="btc-price" value="">' :
val;
}
},
// ## 03 // Price
{
data: null, // Price
render: function(data, type, row, meta) {
return row.last[row.last.length - 1].toFixed(2);
}
},
// ## 04 // Difference
{
data: null, // Difference
render: function(data, type, row, meta) {
var val = (row.last[row.last.length - 1] - row.last[row.last.length - 2]).toFixed(2);
var colour = val < 0 ? 'red' : 'green'
return type === 'display' ?
'<span style="color:' + colour + '">' + val + '</span>' :
val;
}
},
// ## 05 // Price
{
data: null, // Price
render: function(data, type, row, meta) {
return row.last[row.last.length - 1].toFixed(2);
}
}
]
});
});
</script>

Display many charts with data of the same source javascript ( map (key,value) )

I have a map of this form
Object{485:Array[4],2072:Array[4],9665:Array[3]...}
I would like to display a chart per key.
I have an example which is similar to what i'm looking for and i tried to display my values in many charts : In this example, my key is : car_id
First step : sort my array to get a map with my keys. It works fine. But the second one is not working... I would like to display a chart per data based on car_id and per panel bootstrap...
What am I doing wrong ?
Thank you
<html >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
</head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript --><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.0/Chart.min.js"></script>
<script src=" https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.0/Chart.min.js"></script>
<body >
<div >
<div class="panel panel-default">
<div class="panel-heading">Panel heading without title</div>
<div class="panel-body">
<canvas id="myChart" width="400" height="400"></canvas>
</div>
</div>
</div>
</body>
<script>var json = {
'cars': [{
"car_id": "1",
"price": "925",
"full_option": "EEEE"
}, {
"car_id": "1",
"price": "990",
"full_option": "DDDDD"
}, {
"car_id": "2",
"price": "500",
"full_option": "FFF"
}, {
"car_id": "2",
"price": "900",
"full_option": "GGGGGGG"
}, {
"car_id": "4",
"price": "900",
"full_option": "JJJ"
}]
};
var car_array = json.cars.reduce((prev, t, index, arr) => {
if (typeof prev[t.car_id] === 'undefined') {
prev[t.car_id] = [];
}
prev[t.car_id].push(t);
return prev;
}, {});
Object.keys(car_array).forEach(i => {
var array_of_cars_with_same_id = car_array[i];
for (var i=0; i<=array_of_cars_with_same_id.length-1;i++){
console.log(array_of_cars_with_same_id[i].price);
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [array_of_cars_with_same_id[i].full_option],
datasets: [{
label: '# of Votes',
data: [array_of_cars_with_same_id[i].price]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
console.log("AAAAAAAAAAAAA");
});
</script>
There are a couple of problems with your code.
First, you are only using a single canvas element. Each chart needs its own canvas element. Because of this every chart you add simply renders on top of the prior chart.
At a minimum, you have to give each item a new canvas. You could change your code to accomplish that.
Change the root element for the charts to a basic <div> element that you will append the charts to.
<div class="panel-body">
<div id="chart-holder"></div>
</div>
I would create a variable to hold the cart count, and the root element.
var chart_holder = $('#chart-holder');
var chart_count = 0;
Change the for loop to use these new variables.
for (var i = 0; i <= car_type.length - 1; i++) {
chart_holder.append('<canvas id="myChart' + chart_count + '" width="400" height="400"></canvas>')
var ctx = $("#myChart" + chart_count);
var data = [];
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [car_type[i].full_option],
datasets: [{
label: '# of Votes',
data: [car_type[i].price]
}]
},
options: chart_opts
});
chart_count++;
}
This will create a new chart for each object in each array.
I created a fiddle to demonstrate.
Based on the data, however, I would recommend a different approach. I would create a single chart per unique key, rather than a chart for every element.
You would need to parse each array to pull out labels and data for each chart. Here is an example that would get that data out of each array. There is a variable to capture the data for the chart and the labels for the chart.
var car_data = [], car_labels = [];
for (var i = 0; i <= car_type.length - 1; i++) {
car_data.push(car_type[i].price);
car_labels.push(car_type[i].full_option);
}
We can pass car_data and car_labels to the Chart.js initialization.
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: car_labels,
datasets: [{
label: 'Car Type ' + ct,
data: car_data
}]
},
options: chart_opts
});
Here is a fiddle to demonstrate a single chart per car_id.

Real Time Chart Generation using epoch.js

I am trying to create a simple real time chart using epoch.js which updates itself on a click event.
My code posted below has a total of 3 functions. They are:
1) generate a random value
2) generate the current date and time in milliseconds.
3) onclick event that updates chart datapoints.
Though I have datapoints in the right format as required for the chart. I am unable to update it .
Appreciate any help on find out as to why the graph is not working as it should.
///////////////this function generates the date and time in milliseconds//////////
function getTimeValue() {
var dateBuffer = new Date();
var Time = dateBuffer.getTime();
return Time;
}
////////////// this function generates a random value ////////////////////////////
function getRandomValue() {
var randomValue = Math.random() * 100;
return randomValue;
}
////////////// this function is used to update the chart values ///////////////
function updateGraph() {
var newBarChartData = [{
label: "Series 1",
values: [{
time: getTimeValue(),
y: getRandomValue()
}]
}, ];
barChartInstance.push(newBarChartData);
}
////////////// real time graph generation////////////////////////////////////////
var barChartData = [{
label: "Series 1",
values: [{
time: getTimeValue(),
y: getRandomValue()
}]
}, ];
var barChartInstance = $('#barChart').epoch({
type: 'time.bar',
axes: ['right', 'bottom', 'left'],
data: barChartData
});
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js">
</script>
<script src="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/d3.min.js">
</script>
<script src="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/epoch.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/epoch.min.css">
</head>
<div id="barChart" class="epoch category10" style="width:320px; height: 240px;"></div>
<p id="updateMessage" onclick="updateGraph()">click me to update chart</p>
You are pushing the wrong object to barChartInstance when updating the graph. You need to just push the array containing the new data point, instead of pushing the full configuration again.
function updateGraph() {
var newBarChartData = [{time: getTimeValue(), y:getRandomValue()}];
/* Wrong: don't use the full configuration for an update.
var newBarChartData = [{
label: "Series 1",
values: [{
time: getTimeValue(),
y: getRandomValue()
}]
}, ];
*/
barChartInstance.push(newBarChartData);
}
///////////////this function generates the date and time in milliseconds//////////
function getTimeValue() {
var dateBuffer = new Date();
var Time = dateBuffer.getTime();
return Time;
}
////////////// this function generates a random value ////////////////////////////
function getRandomValue() {
var randomValue = Math.random() * 100;
return randomValue;
}
////////////// this function is used to update the chart values ///////////////
function updateGraph() {
var newBarChartData = [{time: getTimeValue(), y:getRandomValue()}];
/*
var newBarChartData = [{
label: "Series 1",
values: [{
time: getTimeValue(),
y: getRandomValue()
}]
}, ];
*/
barChartInstance.push(newBarChartData);
}
////////////// real time graph generation////////////////////////////////////////
var barChartData = [{
label: "Series 1",
values: [{
time: getTimeValue(),
y: getRandomValue()
}]
}, ];
var barChartInstance = $('#barChart').epoch({
type: 'time.bar',
axes: ['right', 'bottom', 'left'],
data: barChartData
});
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js">
</script>
<script src="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/d3.min.js">
</script>
<script src="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/epoch.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/epoch.min.css">
</head>
<div id="barChart" class="epoch category10" style="width:320px; height: 240px;"></div>
<p id="updateMessage" onclick="updateGraph()">click me to update chart</p>

javascript conditional before push?

Ok I have a graph using Highcharts.JS that is populated by an api call providing it with XML data.
I have managed to get the data to push and display on the graph as such, but now I am having the issue of "What happens when there is no data for "x" component" In which I found out that it makes the whole graph blank until you click to hide "x" component on the legend.
So I was thinking that I could probably do some conditional to have it check if there is actually data in the array that is made from the XML.
<!DOCTYPE html>
<html>
<head>
<title>Graph</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/highcharts.js"> </script>
<script>
$(document).ready(function() {
var sgaxml = 'https://sga.quickbase.com/db/bjmdensiu?apptoken=beadyrucxguavbx5isubd6iaqpe&act=API_DoQuery&query=%7B14.EX.%27_FID_9%7D&clist=7.24.25.26.27.28.29.30.31.32.33.34.35.36.37'
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Components Over Time'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Concentration%'
}
},
series: []
};
// Load the data from the XML file
$.get(sgaxml, function(xml) {
// Split the lines
var xml = $(xml).find('record');
// Variables for the component series
var seriesH = {
name: 'Hydrogen',
data: []
};
var seriesHe = {
name: 'Helium',
data: []
};
var seriesO = {
name: 'Oxygen',
data: []
};
var seriesHs = {
name: 'Hydrogen Sulfide',
data: []
};
var seriesN = {
name: 'Nitrogen',
data: []
};
var seriesC = {
name: 'Carbon Dioxide',
data: []
};
var seriesM = {
name: 'Methane',
data: []
};
var seriesE = {
name: 'Ethane',
data: []
};
var seriesP = {
name: 'Propane',
data: []
};
var seriesIb = {
name: 'Iso-Butane',
data: []
};
var seriesNb = {
name: 'N-Butane',
data: []
};
var seriesIp = {
name: 'Iso-Pentane',
data: []
};
var seriesNp = {
name: 'N-Pentane',
data: []
};
var seriesHex = {
name: 'Hexanes+',
data: []
};
xml.each(function (i, record) {
options.xAxis.categories.push(new Date(parseInt($(record).find('sample_date').text())));
seriesH.data.push(parseFloat($(record).find('hydrogen').text()));
seriesHe.data.push(parseFloat($(record).find('helium').text()));
seriesO.data.push(parseFloat($(record).find('oxygen').text()));
seriesHs.data.push(parseFloat($(record).find('hydrogen_sulfide').text()));
seriesN.data.push(parseFloat($(record).find('nitrogen').text()));
seriesC.data.push(parseFloat($(record).find('co2').text()));
seriesM.data.push(parseFloat($(record).find('methane').text()));
seriesE.data.push(parseFloat($(record).find('ethane').text()));
seriesP.data.push(parseFloat($(record).find('propane').text()));
seriesIb.data.push(parseFloat($(record).find('iso_butane').text()));
seriesNb.data.push(parseFloat($(record).find('n_butane').text()));
seriesIp.data.push(parseFloat($(record).find('iso_pentane').text()));
seriesNp.data.push(parseFloat($(record).find('n_pentane').text()));
seriesHex.data.push(parseFloat($(record).find('hexanes_').text()));
});
console.log(seriesO);
options.series.push(seriesH);
options.series.push(seriesHe);
options.series.push(seriesO);
options.series.push(seriesHs);
options.series.push(seriesN);
options.series.push(seriesC);
options.series.push(seriesM);
options.series.push(seriesE);
options.series.push(seriesP);
options.series.push(seriesIb);
options.series.push(seriesNb);
options.series.push(seriesIp);
options.series.push(seriesNp);
options.series.push(seriesHex);
console.log('options: ', options);
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<div id="container" style=" width: 1000px; height: 600px; margin: 0 auto "></div>
</body>
</html>
<!--
XML FROM CALL
=============
<qdbapi>
<action>API_DoQuery</action>
<errcode>0</errcode>
<errtext>No error</errtext>
<dbinfo>
<name>RESULT</name>
<desc/>
</dbinfo>
<variables>
<co2>Carbon Dioxide</co2>
<methane>methane</methane>
</variables>
<chdbids></chdbids>
<record>
<sample_date>1386892800000</sample_date>
<hydrogen>0.002</hydrogen>
<helium>0.114</helium>
<oxygen/>
<hydrogen_sulfide/>
<nitrogen>1.926</nitrogen>
<co2>0.454</co2>
<methane>82.163</methane>
<ethane>6.353</ethane>
<propane>4.760</propane>
<iso_butane>0.618</iso_butane>
<n_butane>1.819</n_butane>
<iso_pentane>0.491</iso_pentane>
<n_pentane>0.544</n_pentane>
<hexanes_>0.756</hexanes_>
<update_id>1408654196361</update_id>
</record>
<record>
<sample_date>1383782400000</sample_date>
<hydrogen>0.006</hydrogen>
<helium>0.038</helium>
<oxygen/>
<hydrogen_sulfide/>
<nitrogen>0.512</nitrogen>
<co2>0.844</co2>
<methane>83.178</methane>
<ethane>8.678</ethane>
<propane>3.631</propane>
<iso_butane>0.493</iso_butane>
<n_butane>1.097</n_butane>
<iso_pentane>0.342</iso_pentane>
<n_pentane>0.371</n_pentane>
<hexanes_>0.810</hexanes_>
<update_id>1408981434690</update_id>
</record>
<record>
<sample_date>1369699200000</sample_date>
<hydrogen>0.004</hydrogen>
<helium>0.060</helium>
<oxygen/>
<hydrogen_sulfide/>
<nitrogen>1.684</nitrogen>
<co2>0.443</co2>
<methane>77.742</methane>
<ethane>10.430</ethane>
<propane>6.842</propane>
<iso_butane>0.587</iso_butane>
<n_butane>1.482</n_butane>
<iso_pentane>0.232</iso_pentane>
<n_pentane>0.249</n_pentane>
<hexanes_>0.245</hexanes_>
<update_id>1408981112624</update_id>
</record>
</qdbapi>
I've attempted to us isnan() as I was told it would be doable with it, but that didn't have any results.
There is already a way to handle this in highcharts. See noData.
noData: {
style: {
fontWeight: 'bold',
fontSize: '15px',
color: '#303030'
}
}
You need to include an extra library (modules/no-data-to-display.js) from highcharts but it is dead simple.

JSP JSON with Google Charts - Line Charts

my graph didn't load up. I try to parse JSON from an JSP page to HTML page with javascript.
I don't know what is the problem. This is the details :
My HTML Page :
<!DOCTYPE html>
<html>
<head>
<title>Google Chart with jsp Mysql Json</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var obj="";
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
url : 'getDataGlucose.jsp',
dataType:'json',
success : function(glucoseData) {
obj = JSON.stringify(glucoseData)
alert('Pass? : '+obj);
},
error : function(xhr, type) {
alert('server error occoured')
}
});
var google_data = {
"cols": [{
"type": "number"
}, {
"type": "number"
}],
rows: []
};
for (var i = 0; i < obj.length; i++) {
google_data.rows.push({
c: [{
v: obj[i].xValue
}, {
v: obj[i].glucose
}]
});
}
var data = new google.visualization.DataTable(google_data);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
var options = {
title: 'Glucose Data Intake',
hAxis: {
title: 'Intake'
},
curveType: 'function',
vAxis: {
title: 'mmHg'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
My generate JSON from JSP page :
[{"glucose":5.5,"xValue":0}, {"glucose":6.2,"xValue":1}, {"glucose":5.8,"xValue":2}, {"glucose":7,"xValue":3}, {"glucose":6,"xValue":4}, {"glucose":7.5,"xValue":5}, {"glucose":6,"xValue":6}, {"glucose":5.5,"xValue":7}, {"glucose":6,"xValue":8}, {"glucose":5.8,"xValue":9}]
Found my way out. I changed from :
obj = JSON.stringify(glucoseData);
to
obj = eval('(' + JSON.stringify(glucoseData) + ')');

Categories