I am currently busy with setting up a business intelligence environment for Elderly Patients. The elderly are wearing a bracelet that measures acceleration and their heart rate.
The heart rate part is going to be a static chart (not a real time one), I have finished that one. The whole environment is pretty much done actually. Except for the real-time acceleration line chart.
So I would like to use the real time life chart of CanvasJS as what they offer seems about right. The problem is I am pretty knew with javascript.
This is the code for the real life line chart:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Live Random Data"
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.
for (var j = 0; j < count; j++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}
chart.render();
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
</script>
<script type="text/javascript" src="/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
As you can see, it is a real chart but it behaves off of random (static) data. I have my database full of data that is generated by the accelerometer.
My question is: How do I make this chart use my data from my database instead of random data? I was thinking around the lines of making an array that is filled with my database data and then use the variable of that array as the source of the data used for the chart.. But I don't know.
I hope I have given you enough info.
You can find the answer here.
Just so that the answer remains here, in case the link is broken.
Here is how you can display MySQL data in CanvasJS,
Create a PHP service that returns data in JSON format.
HTML page that does AJAX request to the server and fetches the data. After getting the data, it renders a Chart.
EXAMPLE:
1. PHP Service to return JSON Data
<?php
header('Content-Type: application/json');
$con = mysqli_connect("127.0.0.1","user","password","canvasjssampledb");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}
else
{
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM sales");
while($row = mysqli_fetch_array($result))
{
$point = array("label" => $row['product'] , "y" => $row['total_sales']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
2. HTML Page to Fetch Data and render Chart
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script src="jquery.js"></script>
<script src="canvasjs.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: result
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
Related
Briefly, i work on to create a Wordpress plugin. In this plugin, i need a progress bar that moving on according to background process. So, I determined a specific php file which contains my custom functions. Let's call this 'func.php' . Also, there is a file that acts as plugins main page file. We can call it 'main.php' .
So; I designed a concept in my head. On the main page, when I click begin button (named 'buttonbegin'), a jquery post being sent to func.php . I can control this POST value with these codes in func.php:
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'buttonbegin':
func1();
break;
case 'otherbutton':
func2();
break;
}
}
After it, func1 executes. In this function, i had these codes for testing:
function func1() { ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
var itemnumber=0;
for (var i = 1; i <= 3000; i++) { //it should be execute 3000 times because of nature of process
itemnumber++;
if (itemnumber == 30) {
var value = "mystring";
var ajaxurl = 'fullurl+pluginsdirectory/main.php', //func.php and main.php are in same folder
data = {'action': value};
$.post(ajaxurl, data, function (response) {
});
itemnumber=0;
}
}
});
</script>
<?php
}
At this point in this func1, I wanna do another jquery post to make a trigger mechanism for progress bar on main.php . And finally, there is some javascript code to control this last jquery post and expand 1% progress bar. Here is the script codes in main.php :
<script type="text/javascript"> //below are for the first process i told
var width = 0;
var addition = 1;
jQuery(document).ready(function($) {
$('#buttonbegin').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'fullurl/func.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
});
});
//actual part starts here
var continuous = setInterval(function() {
var code = <?php echo !isset($_POST['action']) ?>; // the source of the problem
if(!code) {
var percent = $("#myBar").width() / $("#myBar").parent().width() * 100;
if (percent == 100) {
clearInterval(continuous);
}
var element = document.getElementById("myBar");
element.style.width = (width+addition) + "%";
element.innerHTML = (width+addition) * 1 + "%";
width = width + addition;
}
}, 1000);
});
</script>
But it doesn't work. When i print the 'code' variable with console.log, I see NaN value. The php code inside script tags doesn't work properly. Is there any mistake? Or is there another simpler way to do whole process?
Note: Necessary jquery cdn links are included in main.php and func.php both. This is how its look like:
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>
I am very new to javascript (jquery/json) I have written this code to render a chart of CanvasJS with a php/json data fetching script along with it.
However the chart won't show, when I implement my code in to it. When I used Console.log() in web browser to find the ReferenceError it says: Can't find variable: $ ...Chart.html:11
I have tried many things and I have read many [duplicate] question/answers saying that I didn't load the Jquery Library and a bunch of other options. I have tried implementing this line:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
And I have tried many variables, but I don't think I understand what I can use more in these two codes I have..
Any point into the right direction would be great.
Chart.html
<!DOCTYPE HTML>
<html>
<script type="text/javascript" src="canvasjs.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
<head>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var dataPoints = [];
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: dataPoints
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
In the above code, it concerns this part:
$(document).ready(function () {
and my php for the JSON data fetching: data.php
<?php
//header('Content-Type: application/json');
$con = mysqli_connect("localhost","root","","WebApplication");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}
else
{
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM info");
while($row = mysqli_fetch_array($result))
{
$point = array("x" => $row['id'] , "y" => $row['acceleration']);
array_push($data_points, $point);
}
$json = json_encode($data_points, 32); //define('JSON_NUMERIC_CHECK',32); // Since PHP 5.3.3
$json = str_replace("\"", "", $json); //replace all the "" with nothing
echo $json;
}
mysqli_close($con);
?>
I know that the stack overflow community always require more info, but for god sake, I don't know anymore, and I really want to learn this.
EDIT-1:
This is what I have know, yet no result.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
<script type="text/javascript" src="canvasjs.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var dataPoints = [];
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: dataPoints
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
EDIT-2:DEFAULT CODE, WHICH WORKS:
This is the default code that doesn't use my data.php code and uses randomized data points as data-source. It's from Canvasjs and it works fine.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.
for (var j = 0; j < count; j++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}
chart.render();
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:600px;">
</div>
</body>
</html>
It looks like jQuery is being loaded after canvasJS. If Canvasjs needs to use jQuery, it will need to have jQuery loaded first. Try switching those lines so jQuery is loaded on top, and it will probably fix your error.
EDIT: Actually, it seems that the CDN that hosts your jQuery doesn't use $ as the name of your main jQuery object. If you change $ to "jQuery" that error should be resolved. For example:
$(document).ready
would become:
jQuery(document).ready
same with $.getJson
It looks like Jquery isn't being loaded properly, and I'm thinking it's because of your unconventional practice of including the external scripts directly after the element. Try moving them down to just before your own script, inside the head.
Edit: the post was updated and apparently this didn't help.
SOLVED IT
First include this line:
than include this line: BELOW the code, not above it.
Than go to my data.php and comment (or delete) this line: //$json = str_replace("\"", "", $json); //replace all the "" with nothing
why u ask? Well because CanvasJS requires Strings and not separate characters/integrers.
So that the output will be:
[{"x":"1","y":"5"},{"x":"2","y":"5"},{"x":"3","y":"4"},{"x":"4","y":"1"},{"x":"5","y":"8"},{"x":"6","y":"9"},{"x":"7","y":"5"},{"x":"8","y":"6"},{"x":"9","y":"4"},{"x":"10","y":"7"},{"x":"14","y":"7"},{"x":"15","y":"7"}]
Instead of:
[{x:1,y:5},{x:2,y:5},{x:3,y:4},{x:4,y:1},{x:5,y:8},{x:6,y:9}...etc.
I have data in a path static/data.json.I am trying to plot chart using google charts.I want to take out data in data.json file and use it for google charts.
data.json is given below
data = '[{"k": "RAM" , "v":0.515625},{"k": "Camera" , "v":0.515625},{"k": "Design" , "v":0.05},{"k": "Processor" , "v":0},]';
my html code is in template/isworked.html.
Below code is isworked.html
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="application/json" src="static/d.json"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
var mydata = JSON.parse(data);
function drawChart() {
// Create the data table.
//loading data from json
var data = new google.visualization.DataTable();
data.addColumn('string', 'Feature');
data.addColumn('number', 'Positive');
var f,n;
for(var i = 0 ; i<data.length;i++){
f = data[i].k
n = data[i].v
data.addRows([[f,n]])
}
// Set chart options
var options = {'title':'Pie Chart',
'width':800,
'height':700};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
I am not able to plot graph.
This data.json is generated from a python script. I am running everyting using flask framework in Ubuntu
I have no experience in this topic. Can anybody help me?
UberKaeL is correct.
update:
corrected multiple problems with the code and data, e.g., the trailing comma in the data. It works now ... click the "Run Code Snippet" button.
"mydata" is the problem. You are attempting to use data before the json file has loaded. That triggers the error. And mydata is not used for anything. You also need to add a DIV to hold the pie chart. The code snippet below works, but the json data is incorrect for drawing a pie chart. Correct the data and it should work for you.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var mydata = [{"k": "RAM" , "v":0.515625},{"k": "Camera" , "v":0.515625},{"k": "Design" , "v":0.05},{"k": "Processor" , "v": 0}];
</script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Feature');
data.addColumn('number', 'Positive');
var f,n;
for(var i = 0 ; i<mydata.length;i++){
f = mydata[i].k
n = mydata[i].v
data.addRows([[f,n]])
}
var options = {'title':'Pie Chart', 'width':800, 'height':700};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
After a while it seems like your page runs the code before loading the json file. Reading json like that is not a good practice, is better to do an AJAX request like jQuery.getJSON()
so if your are using jQuery do this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON</title>
</head>
<body>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
var mydata=jQuery.getJSON("static/d.json");
if(mydata) {
alert("yay worked");
}
else {
alert("something is wrong");
}
//rest of your code
//function drawChart() { ...
</script>
</body>
</html>
Also is a good practice to enclose your program inside a $(document).ready and remember to remove last comma in your JSON:
data = '[{"k": "RAM" , "v":0.515625},{"k": "Camera" , "v":0.515625},{"k": "Design" , "v":0.05},{"k": "Processor" , "v":0}]';
#Robert gives you a good answer about how to draw the chart
You are not using mydata where you put json read values.
data contains an empty new google.visualization.DataTable() and the loop are reading values from it, not from mydata.
I'm trying to get the data from my fusion tables. when I use SELECT query the data show successfull. but when I'm using SUM and MAXIMUM query the firebug show error :
"SyntaxError: syntax error
Error 500 (There's a p"
when i test my query from fusion query the query works.
when i search based from firebug error, it's because i'm not specify the script tag to script type="text/javascript" .
but i think it's not actualy the error i get, because yesterday my code works. and today i don't know why my code doesn't works.
Can anybody help me? thanks for any help.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// Fusion Table data ID
var FT_TableID = '1j1AG2s_IgNBQmm0QP9yYGHFg2_rNSZoEH4ee80In';
var FT_TableIDSP = '1O5aIPnHBCimWsYg0gOXIeRH6eL-6byD95Nd2pdXR';
google.load('visualization', '1', {'packages':['corechart', 'table', 'geomap']});
function getKP() {
// set the query using the parameters
var FT_Query_KP = "SELECT 'Kelompok Penanam', count() FROM "+FT_TableID+" GROUP by 'Kelompok Penanam' ORDER by 'idPenanam'";
//var FT_Query_KP = "SELECT SUM('Tinggi Pohon') FROM 1O5aIPnHBCimWsYg0gOXIeRH6eL-6byD95Nd2pdXR";
//var FT_Query_KP = "SELECT MAXIMUM('Tinggi Pohon') FROM 1O5aIPnHBCimWsYg0gOXIeRH6eL-6byD95Nd2pdXR";
var queryText = encodeURIComponent(FT_Query_KP);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(KP);
}
// Set a callback to run when the Google Visualization API is loaded.
function KP(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var KPname = response.getDataTable().getValue(0,0);
document.getElementById('dropdownKP').innerHTML = KPname;
}
</script>
<script type="text/javascript">
getKP();
</script>
</head>
<body>
<div id="dropdownKP"></div>
</body>
</html>
We've identified a problem in the code for summaries with no second column in the projection; pie charts are the only ones that allow that, so it slipped past us. We are working on a fix and will update this question when it's available.
That said, the pie charts resulting from such queries wouldn't be too useful because they only have a single value.
Thanks Rod and Juvian, I change code from google visualization query to google fusion v1 query from this link
I am using the code below to graph data into flot, and when I print out dataOne, it returns properly formatted values for flot, however when I set it as the data for flot to graph, flot forms a graph but then has no data points?
<!DOCTYPE HTML>
<html>
<head>
<title>AJAX FLOT</title>
<script language="javascript" type="text/javascript" src="../../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.time.js"></script>
</head>
<body>
<div id="placeholder" style="width: 100%;height: 600px;"></div>
<script language="javascript" type="text/javascript">
var options = {
lines: {
show: true
},
points: {
show: true
},
yaxis: {
min: "0",
max: "1023"
},
xaxis: {
mode: "time"
}
};
function update() {
$.ajax({
url: "http://localhost/data.php",
context: document.body
}).done(function(response) {
dataOne = response;
var d = "[" + dataOne + "]";
var plot = $.plot($('#placeholder'), [d], options);
setTimeout(update, 1000);
});
}
update();
</script>
</html>
Finally to the root of the problem. If it's valid JSON, dataOne must be an array of arrays:
[[1412393775000, 277], [1412393777000, 277], [1412393778000, 277]]
Note the extra brackets. Check your console.log carefully.
Doing this:
var d = "[" + dataOne + "]";
in JavaScript, automatically converts it to a string.
What you need is an array of array of array (the inner most is a point, the second is a series, the outer is a collection of series):
var d = [dataOne];
And then just
var plot = $.plot($('#placeholder'), d, options);
For those of you who may want to do something similar, here is the code I used to finally make it work. :)
First off, the page that produced the value the PHP file collected was incorrect. The Arduino was using AJAX to update the value every second, but I realised this was stupid as the page was called every second from the main AJAX call which called data.php which then called this page. So I removed the AJAX from the Arduino Web Server code.
Since the code was not working and I had spent hours trying I started to look around for alternatives. In highcharts.js I found some AJAX code, and decided to try it. Here is the code I ended up with:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>AJAX FLOT</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script language="javascript" type="text/javascript" src="../../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.time.js"></script>
</head>
<body>
<div id="placeholder" style="width: 100%;height: 600px;"></div>
<div id="div" style="width: 100%; height: 100px;"></div>
<script type="text/javascript">
var options = {
lines: {
show: true
},
points: {
show: true
},
xaxis: {
mode: "time"
}
};
window.setInterval(function(){
$.getJSON('http://localhost/data.php', function (csv) {
dataOne = csv;
var plot = $.plot($('#placeholder'), [dataOne], options);
});
}, 1000);
</script>
</html>
After that, I had to get the data.php working properly. I had a problem where
file_get_contents
Would not only get the output of the Arduino, but also many of the tags surrounding it. This stuffed up my data. So I gave up with the proper html tags and just printed out the plain value. So if you went to the page source of the Arduino's output, there are no tags surrounding the value, all you see is a number. So that stopped that issue.
Here is the php code I use to format the values:
<?php
$file = "data.txt";
$webpage = "http://192.168.1.177/";
$t = time() * 1000;
$current = file_get_contents($file);
$data = file_get_contents($webpage);
if ($current < "1") {
$current .= '[[' . $t . ', ' . $data . ']]';
file_put_contents($file, $current);
echo $current;
}
else {
$cut = substr($current, 0, -1);
$cut .= ', [' . $t . ', ' . $data . ']]';
file_put_contents($file, $cut);
echo $cut;
}
?>
To get the data into the appropriate brackets, you can see that when no data is present in the file, the if statement does not include a comma and space, because there is no other set of data to separate from. As soon as one value is in the file, I use substr to get rid of the last containing bracket, then append the comma, space and then values, with the containing bracket put again at the very end of the data where it should be.
Anyway, this ended up working like a dream. Thanks for everyones help :)