canvasjs live updating data from database - javascript

I am new to web based visualization tool I used chartjs before but I did not find any solution for chartjs so, I transferred to canvasjs.Now I'm done creating the chart and it is successfully shown, thus I want to make it moving without refreshing because the data from the database is constantly moving. Here is my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
window.onload = function () {
$.getJSON("json.php", function(result){
var dps= [];
//Insert Array Assignment function here
for(var i=0; i<result.length;i++) {
dps.push({"label":result[i].ts, "y":result[i].ph});
}
//Insert Chart-making function here
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled:true,
panEnabled:true,
animationEnabled:true,
title:{
text: "myChart from mySQL database"
},
axisX:{
title: "TimeStamp"
},
axisY:{
title: "myDataPoints",
minimum: 0
},
data: [{
type: "spline",
dataPoints:
dps
}]
});
chart.render();
});
}
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
now, I would like to ask for help out there What do I need to keep this chart moving...??

If you want the lines to move, you need to remove dataPoints from the beginning of the array. You can do so using shift function in JS.
for(var i=0; i<result.length;i++) {
dps.push({"label":result[i].ts, "y":result[i].ph});
dps.shift();
}
This would do the trick for you.

Related

Make bar chart using canvas.js

Hello I am new to JavaScript but having difficulty with the generation of charts using the canvas.js library. The step that I am failing to replicate is the example on canvasjs website https://canvasjs.com/docs/charts/how-to/create-charts-from-csv/ for generating a chart using a csv document. Will I have to approach differently since I am hosting from google sheets?
My current code is:
<!DOCTYPE html>
<html>
<head>
<title>TEst</title>
<script type="text/javascript">
window.onload = function(){
var dataPoints = [];
function getDataPointsFromCSV(csv) {
var dataPoints = csvLines = points = [];
csvLines = csv.split(/[\r?\n|\r|\n]+/);
for (var i = 0; i < csvLines.length; i++)
if (csvLines[i].length > 0) {
points = csvLines[i].split(",");
dataPoints.push({
x: parseFloat(points[0]),
y: parseFloat(points[1])
});
}
return dataPoints;
}
//Replace text file's path according to your requirement.
$.get("https://docs.google.com/spreadsheets/d/12o9ekzln8KB3Uyg2fVou6UtIUlrC5GC973Ttk6GsjKs/edit?usp=sharing",function(data) {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Chart from CSV",
},
data: [{
type: "line",
dataPoints: getDataPointsFromCSV(data)
}]
});
chart.render();
});
}
</script>
</head>
<body>
<p>it worked:</p>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
When I inspect with chrome I get the following error.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Hello there is already a good answer to this question, I added a link to the bottom of this answer.
It sounds like Google is not allowing you to load the data from their website.
Try replacing your dataPoints: getDataPointsFromCSV(data) with some example data from chart.js's site to make sure the rest of your code is working.
No 'Access-Control-Allow-Origin' header is present on the requested resource. with github sites

Google charts not displaying on browser

Below is the code I have for displaying the Chart . I am unsure as to what is going wrong here.
Please bear with me , this is the first time I have asked a question in this forum.
Thank you for your help
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(DrawChart);
function DrawChart() {
var data = google.visualization.arrayToDataTable([
['Short Shipment', 'Product Questions', 'Product Service Request', 'Billing Question','Product Issue','Return or Exchange Request','- None -'],
[1, 3, 4, 8, 8, 11, 283]]);
var options = {
chart: {
title: 'Case Issue Summary'
},
bars: 'horizontal'
};
var chart = new google.charts.Bar(document.getElementById('BarChartCase'));
chart.draw(data, options);
}
</script>
</head>
<body padding="0.5in 0.5in 0.5in 0.5in" size="Letter">
<div id="BarChartCase" style="width: 200px; height: 100px;"> </div>
</body>
</html>
Your code is 99/100 copied from developers.google.com/chart/....
The only changes you made is the width and height to 200 and 100.
Change it to a greater number and you'll be able to see your bar chart.
codepen copy

Can't get rid of XML in "variables"

This is involving Intuit's Quickbase. I am trying to use Highcharts.JS and have the data loaded via XML into the graph. The problem I am currently having is that in the variables I have two variables that do not need to be on the graph that relate to something else entirely.
<!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>CoT</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>
<!-- JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Components Over Time'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Units'
}
},
series: []
};
// Load the data from the XML file
$.get('https://dbname.quickbase.com/db/?apptoken=&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', function(xml) {
// Split the lines
var $xml = $(xml);
// push categories
$xml.find('variables').each(function(i, variables) {
options.xAxis.categories.push($(variables).text());
});
// push series
$xml.find('record').each(function(i, record) {
var seriesOptions = {
name: $(record).find('methane').text(),
data: [],
};
// push data points
$(record).find('methane').each(function(i, point) {
seriesOptions.data.push(
parseInt($(point).text())
);
});
// add it to the options
options.series.push(seriesOptions);
});
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<!-- 3. Add the container -->
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
The following has also been tried in the push categories to no success
$xml.find('variables:not(iol):not(__iol)').each(function(i, variables) {
options.xAxis.categories.push($(variables).text());
});
Both cause the graph to come back looking like ( http://i.imgur.com/fb8A2uO.jpg )
Edit: This is the XML output
<?xml version="1.0" ?>
<qdbapi>
<action>API_DoQuery</action>
<errcode>0</errcode>
<errtext>No error</errtext>
<dbinfo>
<name>RESULT</name>
<desc></desc>
</dbinfo>
<variables>
<__iol>&rand='+new Date().getTime())};"></__iol>
<iol><img qbu='module' src='/i/clear2x2.gif' onload="javascript:if(typeof QBU=='undefined'){QBU={};$.getScript(gReqAppDBID+'?a=dbpage&pagename=</iol>
</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>
Try
// note the space character between tags ,
// to prevent rendering `<variables />` within xml
$xml.find("variables").replaceWith("<variables> </variables>");
http://jsfiddle.net/xwzox6rg/

Google chart does not appear even if no error

Here is my code to create google chart from csv data. ANd also no error. But even chart does not appear.
Here is the documentation for which works: http://economistry.com/2013/07/easy-data-visualization-with-google-charts-and-a-csv/
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="http://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// grab the CSV
$.get("Chart1-data.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
alert(arrayData);
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
// this view can select a subset of the data at a time
var view = new google.visualization.DataView(data);
view.setColumns([0,1]);
// set chart options
var options = {
title: "A Chart from a CSV!",
hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
legend: 'none'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
});
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
Chart1-data.csv
Category,
A,34
B,23
C,14
D,57
E,18
Other,5
Do I missing anything in the code?
Good news: Your Code is fine! Your CSV file is the bottleneck.
Column names can't be null, means Category, => Category,''
No additional line breaks between data rows, means
A,34
B,23
=>
A,34
B,23
Result:
Category,''
A,34
B,23
C,14
D,57
E,18
Other,5
That is all! :)
There doesn't seem any kind of problem with this Google chart code snippet.
Though in browser console there are some Uncaught JavaScript errors.
Most importantly there is
" Uncaught null "error which is in reference to blank space after "Category" so Category, ' ' should work fine

Trouble with Google charts getting this.J[a].c is undefined

I'm VERY new to google charts and I cant seem to find the problem in my code:
My php file returns:
{"cols":[{"id":"","label":"Time","type":"string"},{"id":"","label":"Max","type":"number"},{"id":"","label":"Average","type":"number"}],"rows":[[{"c":[{"v":"2013-11-19
14:38:00"},{"v":2576},{"v":2144}]},{"c":[{"v":"2013-11-19
14:39:00"},{"v":1960},{"v":1682}]},{"c":[{"v":"2013-11-19
14:40:00"},{"v":1789},{"v":1565}]},{"c":[{"v":"2013-11-19
14:41:00"},{"v":1995},{"v":1654}]},{"c":[{"v":"2013-11-19
14:42:00"},{"v":14647},{"v":11638}]},{"c":[{"v":"2013-11-19
14:43:00"},{"v":7512},{"v":5202}]},{"c":[{"v":"2013-11-19
14:44:00"},{"v":2056},{"v":1681}]},{"c":[{"v":"2013-11-19
14:45:00"},{"v":1874},{"v":1524}]},{"c":[{"v":"2013-11-19
14:46:00"},{"v":1706},{"v":1385}]},{"c":[{"v":"2013-11-19
14:47:00"},{"v":2244},{"v":1667}]},{"c":[{"v":"2013-11-19
14:48:00"},{"v":16198},{"v":13145}]},{"c":[{"v":"2013-11-19
14:49:00"},{"v":17549},{"v":13886}]},{"c":[{"v":"2013-11-19
14:50:00"},{"v":1824},{"v":1513}]},{"c":[{"v":"2013-11-19
14:51:00"},{"v":2299},{"v":1762}]},{"c":[{"v":"2013-11-19
14:52:00"},{"v":20273},{"v":13167}]},{"c":[{"v":"2013-11-19
14:53:00"},{"v":3024},{"v":2231}]},{"c":[{"v":"2013-11-19
14:54:00"},{"v":14386},{"v":10450}]},{"c":[{"v":"2013-11-19
14:55:00"},{"v":16368},{"v":13741}]},{"c":[{"v":"2013-11-19
14:56:00"},{"v":4528},{"v":2717}]},{"c":[{"v":"2013-11-19
14:57:00"},{"v":3655},{"v":2601}]},{"c":[{"v":"2013-11-19
14:58:00"},{"v":3456},{"v":2624}]},{"c":[{"v":"2013-11-19
14:59:00"},{"v":4818},{"v":2917}]}]]}
I would like to draw a graph that plots time on x and then two lines with MAX and AVERAGE values.
I believe the issue Lies somewhere in my HTML/JAVASCRIPT code.
<html>
<head>
<title>Dashboard</title><meta name=keywords /><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><meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<!---->
<style type="text/css">
body { background-color: #ffffff; padding-left: 1%; padding-bottom: 100px; }
footer{font-size:small;position:fixed;right:5px;bottom:5px;}
</style>
<style>h1 {color:white; font-size:24pt; text-align:center;font-family:arial,sans-serif }.menu {color:white; font-size:12pt; text-align:center;font-family:arial,sans-serif; font-weight:bold }table2 {background:black }p {color:black; font-size:12pt; text-align:justify;font-family:arial,sans-serif }p.foot {color:white; font-size:9pt; text-align:center;font-family:arial,sans-serif; font-weight:bold }a:link, a:visited, a:active {color:white}
</style>
</head>
<body>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load("visualization", "1", {"packages":["corechart"]});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
url: "get_sql_data.php",
dataType: "json",
success: function (jsonData) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById("chart_div"));
chart.draw(data, {width: 400, height: 240});
}
});
}
</script>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div><table width=100% bgcolor=black cellpaddin g=0 border=0>
</body>
It seems that your json data are in bad format. cols are ok:
{
"cols":
[
{
"id":"", "label":"Time",
"type":"string"
},
rows have one extra pair [ ... ] which should be removed:
"rows":
[
[
{
"c":[
{"v":"2013-11-19 14:38:00"},
{"v":2576},
{"v":2144}
]
},
To get
"rows":
[
{
"c":[
{"v":"2013-11-19 14:38:00"},
{"v":2576},
{"v":2144}
]
},
See also Google line chart visualization with JSON blob.

Categories

Resources