Loop inside Jquery Chart to make it dynamic - javascript

Im new in Js and Jquery and I have a curiosity about the Jquery Chart that is free to download and I want to make the data inside to be coming from the database to make it dynamic but somehow I find it difficult to loop it in.
here is my sample code, I used PHP to get the database and pass it on a JS variable
<!DOCTYPE HTML>
<html>
<head>
<?php
$link = mysqli_connect("localhost","root","","raksquad_centralized") or die("Error " . mysqli_error($link));
if($link->connect_error){
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM raksquad_centralized.grade";
$result = $link->query($query);
$subject_id= array();
$genAve = array();
while($row = mysqli_fetch_array($result)){
$subject_id[] = $row['subject_id'];
$genAve[]= $row['gen_ave'];
}
?>
<script type="text/javascript">
window.onload = function () {
var DataXAxis = <?php echo json_encode($subject_id); ?>; // X axis that corresponds to students
var DataYAxis = <?php echo json_encode($genAve); ?>; // Y axis that corresponds to grades
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Top Students"
},
animationEnabled: true,
axisY: {
title: "Grades"
},
axisX: {
title: "Students"
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center"
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "General Average",
dataPoints: [
//the area to loop with the value of DataXAxis, DataYAxis
{y: 98, label: "MT1234" },
{y: 72, label: "MT1236"} //corresponds to the barcharts
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="./canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
appreciate for the help, useful for learning :)

I just use a php code to fetch the data, then json encode it.
On the script use json parse

Related

how to display three lines on chart

I create a chart using canvasjs. Values display in chart is from mysql database. All working but the problem is, it showing just 1 line on chart (sensors_pres) from table SensorData on chart not all three sensors_pres, sensors_temperature_data and sensors_humidity.
Other problem is on range slider is not showing hour from 0 to 24, test it. Click in left-up on button all and in right-up you will see the number -1 to 96. How can i solve?
I opened data.php file with browser and all values working correct.
Here is my html&javascript code
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.stock.min.js"></script>
<script type="text/javascript">
window.onload = function () {
$.getJSON("data.php", function (result) {
var stockChart = new CanvasJS.StockChart("chartContainer",{
title:{
text:"StockChart with Numeric Axis"
},
animationEnabled: true,
exportEnabled: true,
charts: [{
axisX: {
crosshair: {
enabled: true,
snapToDataPoint: true
}
},
axisY: {
crosshair: {
enabled: true,
//snapToDataPoint: true
}
},
data: [{
type: "line",
dataPoints: result
}]
}],
rangeSelector: {
inputFields: {
startValue: 00,
endValue: 24,
valueFormatString: "###0"
},
buttons: [{
label: "00",
range: 00,
rangeType: "number"
},{
label: "12",
range: 12,
rangeType: "number"
},{
label: "24",
range: 24,
rangeType: "number"
},{
label: "All",
rangeType: "all"
}]
}
});
stockChart.render();
})
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 450px; width: 100%;"></div>
</body>
</html>
here is my php code:
<?php
header('Content-Type: application/json');
$con = mysqli_connect("fdb30.awardspace.net","3758712_lnd","bogdanutzu97","3758712_lnd");
// 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 SensorData");
while($row = mysqli_fetch_array($result))
{
$point = array("label" => $row['reading_time'] , "y" => $row['sensors_pres'],$row['sensors_temperature_data'],$row['sensors_humidity']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
data: [
{
type: "line",
dataPoints: result1
},
{
type: "line",
dataPoints: result2
},
{
type: "line",
dataPoints: result3
}
]
In your data section add 2 more data sets

JavaScript does not echo values coming from database

The first thing I get values from database with no problem. Then I can echo the values but after The values turn in to null. Somehow the values do not pass this point. Here are my codes.
php and mysql part
$rows = array();
$result = mysql_query("SELECT * FROM kayitlar");
$i=1;
while($row = mysql_fetch_array($result)) {
$rows []= array(
'id' => $row['id'],
'ad' => $row['ad'],
'saat' => $row['saat'],
);
$i++;
}
No problem till this point. Here is the rest of the code that I am having problem
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "title"
},
animationEnabled: true,
axisY: {
title: "Zaman (saat)"
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center"
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "saat",
dataPoints: [
{y:<?php echo json_encode($row['ad']); ?>, label: "<?php echo json_encode($row['saat']); ?> "},
]
}
]
});
chart.render();
}
</script>
here where I stuck <?php echo json_encode($row['ad']); ?> is getting no value
Your $rows array indexed array which contain your keys in every index. So you need to extract your keys value pair from array.
After your while loop completed, add following codes
$arr['ad'] = array_column($rows,"ad");
$arr['saat'] = array_column($rows,"saat");
$arr['id'] = array_column($rows,"id");
Now use this in your jS
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "title"
},
animationEnabled: true,
axisY: {
title: "Zaman (saat)"
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center"
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "saat",
dataPoints: [
{y:<?php echo json_encode($arr['ad']); ?>, label: "<?php echo json_encode($arr['saat']); ?> "},
]
}
]
});
chart.render();
}
</script>
Your array is multidimensional array so simple use array_column to get specific column value from each index and apply json_encode()
<?php echo json_encode(array_column($rows,'ad')); ?>
<?php echo json_encode(array_column($rows,'saat')); ?>

Live data from MySQL with highchart

I found this Highchart live data example Live data. I try to use my own data which is come from MySQL so, I change the $y in live-server-data.php to receive the data after use function fetch_assoc().
HTML Code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/highcharts.js"></script>
</head>
<body>
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
JS
var chart; // global
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 20
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: []
}]
});
});
PHP code
<?php
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed: ".$conn->connect_error);
}
$sql_1 = "SELECT SensorData AS power FROM $tbname where SensorID = '1'";
$result_1=$conn->query($sql_1);
while($row = $result_1->fetch_assoc()){
$y = $row['power'];
}
$conn->close();
header("Content-type: text/json");
multiplied by 1000.
$x = time() * 1000;
$ret = array($x, $y);
echo json_encode($ret);
?>
The graph is moved but it not shows any data.
So I press F12 on Chrome Browser and I found this thing.
I think "14.600" may be the cause of my problem. Please tell me if you know the solution to solve this problem. Thank you so much.
I think the graph required an array that contains numeric values in it. In your case one value is numeric but another one is string so convert all the values to numeric i.e. either integer or float. (Float is preferred here) and pass that array to the graph.

Highcharts xaxis is off by several hours

I'm pulling values from a MySQL database using PHP, and attempting to plot them using Highcharts. The problem I'm finding is the xaxis values seems to be off by 4 hours. Searching through past threads, some people place the useUTC: false in the global chart options, but it did not seem to work for me.
global:{
useUTC: false
}
Here is the code I'm using to set up the chart. I'm a javascript newbie, so it's very possible I did something stupid in here. Any suggestions?
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Temperature Data from XBee</title>
<script src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Wireless Sensor Data: Temperature (F)',
x: -20 //center
},
global: {
useUTC: false
},
yAxis: {
title: {
text: 'temperature'
},
type: 'double',
min: 0,
},
xAxis: {
title: {
text: 'time'
},
type: 'datetime'
},
series: [{
name: 'Temperature',
data: []
}]
}
$.getJSON("data.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.Chart(options);
});
});
</script>
<script src="js/highcharts.js"></script>
<script src="js/themes/grid-light.js"></script>
</head>
<body>
<div id="container" style="min-width: 800px; height: 800px; margin: 0 auto"></div>
</body>
</html>
Here is my PHP code that queries the database and puts the data into the JSON format.
<?php
$con = mysql_connect("localhost","root","raspberry");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xbee", $con);
$result = mysql_query("SELECT time, temperature FROM data WHERE time >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$rows = array();
while($r = mysql_fetch_array($result)) {
extract($r);
$time = strtotime($r[0]);
$time *=1000;
$row[0] = $time;
$row[1] = $r[1];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
This is what my JSON format looks like.
[[1414172722000,73.4],[1414172727000,73.4],[1414172732000,73.4],[1414172737000,75.2],[1414172742000,75.2],[1414172747000,75.2],[1414172753000,73.4],[1414172758000,75.2],[1414172763000,73.4],[1414172768000,75.2],[1414172773000,75.2],[1414172778000,75.2],[1414172783000,75.2],[1414172788000,73.4],[1414172793000,73.4],[1414172798000,75.2],[1414172803000,75.2],[1414172809000,75.2],[1414172814000,75.2],[1414172819000,75.2],[1414172824000,73.4],[1414172829000,75.2],[1414172834000,75.2],[1414172839000,75.2],[1414172844000,75.2],[1414172849000,75.2],[1414172854000,75.2],[1414172860000,75.2],[1414172865000,75.2],[1414172870000,75.2],[1414172875000,75.2],[1414172880000,75.2],[1414172885000,75.2],[1414172890000,75.2],[1414172895000,75.2],[1414172900000,75.2],[1414172905000,73.4],[1414172910000,75.2],[1414172916000,75.2],[1414172921000,75.2],[1414172926000,75.2],[1414172931000,75.2],[1414172936000,75.2],[1414172941000,75.2],[1414172946000,75.2],[1414172951000,75.2],[1414172956000,75.2],[1414172961000,75.2],[1414172966000,73.4],[1414172972000,75.2],[1414172977000,75.2],[1414172982000,73.4],[1414172987000,75.2],[1414172992000,75.2],[1414172997000,73.4],[1414173002000,75.2],[1414173007000,75.2],[1414173012000,75.2],[1414173017000,75.2],[1414173022000,75.2],[1414173028000,75.2],[1414173033000,75.2],[1414173038000,75.2],[1414173043000,75.2],[1414173048000,75.2],[1414173053000,75.2],[1414173058000,75.2],[1414173063000,71.6],[1414173068000,75.2],[1414173073000,75.2],[1414173079000,75.2],[1414173084000,75.2],[1414173089000,75.2],[1414173094000,75.2],[1414173099000,75.2],[1414173104000,75.2],[1414173109000,75.2],[1414173114000,75.2],[1414173119000,75.2],[1414173124000,75.2],[1414173129000,75.2],[1414173135000,75.2],[1414173140000,75.2],[1414173145000,75.2],[1414173150000,75.2],[1414173155000,75.2],[1414173160000,75.2],[1414173165000,75.2],[1414173170000,75.2],[1414173175000,75.2],[1414173180000,75.2],[1414173185000,75.2],[1414173191000,75.2],[1414173196000,75.2],[1414173201000,75.2],[1414173206000,75.2],[1414173211000,75.2],[1414173216000,75.2],[1414173221000,75.2],[1414173226000,75.2],[1414173231000,75.2],[1414173236000,75.2],[1414173241000,75.2],[1414173247000,75.2],[1414173252000,75.2],[1414173257000,75.2],[1414173262000,75.2],[1414173267000,75.2],[1414173272000,75.2],[1414173277000,75.2],[1414173282000,75.2],[1414173287000,75.2],[1414173292000,75.2],[1414173298000,75.2],[1414173303000,75.2],[1414173308000,75.2],[1414173313000,75.2],[1414173318000,75.2],[1414173323000,75.2],[1414173328000,75.2],[1414173333000,75.2],[1414173338000,75.2],[1414173343000,75.2],[1414173348000,75.2],[1414173354000,75.2],[1414173359000,75.2],[1414173364000,75.2],[1414173369000,75.2],[1414173374000,75.2],[1414173379000,75.2],[1414173384000,75.2],[1414173389000,75.2],[1414173394000,75.2],[1414173399000,75.2],[1414173404000,75.2],[1414173410000,75.2],[1414173415000,75.2],[1414173420000,75.2],[1414173425000,75.2],[1414173430000,75.2],[1414173435000,75.2],[1414173440000,75.2],[1414173445000,75.2],[1414173450000,75.2],[1414173455000,73.4],[1414173461000,75.2],[1414173466000,75.2],[1414173471000,75.2],[1414173476000,75.2],[1414173481000,75.2],[1414173486000,75.2],[1414173491000,75.2],[1414173496000,75.2],[1414173501000,73.4],[1414173506000,75.2],[1414173511000,75.2],[1414173517000,73.4],[1414173522000,75.2],[1414173527000,75.2],[1414173532000,75.2],[1414173537000,75.2],[1414173542000,75.2],[1414173547000,75.2],[1414173552000,73.4],[1414173557000,75.2],[1414173562000,75.2],[1414173567000,75.2],[1414173573000,75.2],[1414173578000,75.2],[1414173583000,75.2],[1414173590000,32],[1414173651000,75.2],[1414173711000,75.2],[1414173771000,73.4],[1414173831000,75.2],[1414173891000,73.4],[1414173951000,75.2],[1414174011000,73.4],[1414174071000,75.2],[1414174131000,73.4],[1414174191000,75.2],[1414174251000,71.6],[1414174311000,73.4],[1414174372000,73.4],[1414174432000,73.4],[1414174492000,73.4],[1414174552000,73.4],[1414174612000,73.4],[1414174672000,73.4],[1414174732000,73.4],[1414174792000,73.4],[1414174852000,73.4],[1414174912000,73.4],[1414174972000,73.4],[1414175032000,73.4],[1414175093000,73.4],[1414175153000,73.4],[1414175213000,73.4],[1414175273000,73.4],[1414175333000,73.4],[1414175393000,73.4],[1414175453000,73.4],[1414175513000,73.4],[1414175573000,73.4],[1414175633000,73.4],[1414175693000,73.4],[1414175753000,73.4],[1414175814000,73.4],[1414175874000,73.4],[1414175934000,73.4],[1414175994000,73.4],[1414176054000,73.4],[1414176114000,73.4],[1414176174000,73.4],[1414176234000,75.2],[1414176294000,75.2]]
I found a solution, not sure if this is the most elegant, but it is producing the correct results now. It looks like when using the strtotime conversion in PHP, it was using the default GMT timezone. In the PHP script, I added the date_default_time_set('UTC') and it works. Hopefully this will help someone in the future.
<?php
$con = mysql_connect("localhost","root","raspberry");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xbee", $con);
$result = mysql_query("SELECT time, temperature FROM data WHERE time >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$rows = array();
while($r = mysql_fetch_array($result)) {
date_default_timezone_set('UTC');
extract($r);
$time = strtotime($r[0]);
$time *=1000;
$row[0] = $time;
$row[1] = $r[1];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
mysql_close($con);
?>

modify Xaxis in highcharts

How can I introduce in the highcharts code an array that comes from a php code?
In the next code php I generate 4 arrays, 3 for Data (TMax ($rows), TMin ($rows1) and Rain ($rows2) and the last one for the days of the consulting ($dia).
$sth = mysqli_query($con,"SELECT City,TMax, Day(Date) As Dia FROM Meteo2 where City= '" . $_SESSION["City"] ."' AND Data BETWEEN '" . split($_SESSION["date8"]) ."' AND '" . split($_SESSION["date9"]) ."'order by Date");
$rows = array();
$dia = array();
$dia['name'] = 'Dia';
$rows['name'] = 'TMAX';
$rows['color'] = '#FF0000';
$cont=1;
while($r = mysqli_fetch_array($sth)) {
$rows['data'][] = $r['TMax'];
$dia['categories'][] = $r['Dia'];
}
$sth = mysqli_query($con,"SELECT City,TMin FROM Meteo2 where City= '" . $_SESSION["City"] ."' AND Data BETWEEN '" . split($_SESSION["date8"]) ."' AND '" . split($_SESSION["date9"]) ."'order by Date");
$rows1 = array();
$rows1['name'] = 'TMIN';
$rows1['color'] = '#00FFFF';
$rows1['var valueSuffix'] = 'ºC';
while($rr = mysqli_fetch_assoc($sth)) {
$rows1['data'][] = $rr['TMin'];
}
mysqli_query($con,"SELECT City,Rain FROM Meteo2 where City= '" . $_SESSION["City"] ."' AND Data BETWEEN '" . split($_SESSION["date8"]) ."' AND '" . split($_SESSION["date9"]) ."'order by Date");
$rows2 = array();
$rows2['name'] = 'RAIN';
$rows2['type'] = 'column';
$rows2['color'] = '#4572A7';
$rows2['var valueSuffix'] = 'mm';
$rows2['var yAxis'] = 2;
while($rr = mysqli_fetch_assoc($sth)) {
$rows2['data'][] = $rr['Rain'];
}
$result = array();
array_push($result,$rows2);
array_push($result,$rows1);
array_push($result,$rows);
array_push($result,$dia);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
When I plot the chart, I can see the line of rain, TMax, TMin, but in the Xaxis by default I have 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15....and what I need is the information of $dia inside categories[]
and when i check the browser I see categories empty...
xAxis: {
categories: []
},
but in the highchart code I have
xAxis: {
categories: ['<?php echo $dia?>']
},
any help please????
Here I show the highcharts code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>www.meteo4u.com/consultaNouformat.html</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
<?php
$city = $_POST["City"];
session_start();
$_SESSION['City'] = $_POST['City'];
$_SESSION['date8'] = $_POST['date8'];
$_SESSION['date9'] = $_POST['date9'];
?>
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("mysql-highcharts.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'spline',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Temperatura Maxima, Temperatura Minima i Precipitacio a <?php echo $city ?>',
x: -20 //center
},
xAxis: {
categories: [<?php echo $dia?>]
},
yAxis: [{
labels: {
format: '{value}°C',
style: {
color: '#FF0000'
}
},
title: {
text: 'Temperatura Maxima',
style: {
color: '#FF0000'
}
}
},{title: {
text: 'Temperatura Minima',
style: {
color: '#00FFFF'
}
}
},{labels: {
format: '{value} mm',
style: {
color: '#4572A7'
}
},
title: {
text: 'Precipitacio',
style: {
color: '#4572A7'
}
},opposite: true
}],
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
},
credits:{
text: 'meteo4u.com',
href:'http://meteo4u.com',
itemStyle: {
fontSize: '40px'
}
},
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>
It looks like $dia is an array is an array, containing an entry called 'categories'. I don't think you can somply echo the array variable in your highcharts code, as dia only exists in php on the server. You are returning the categories inside your json object in the 3rd entry of the array
array_push($result,$dia);
This means you have to read the categories out of the returned json in your highcharts code. Your code is hard to follow, but try this:
xAxis: {
categories: json[3]['categories'];
},
However, I am worried about this line:
series: json
The returned json does not just contain series definitions as it contains the categories as well. It may work, but is not very clean code.

Categories