How do i get updated values from php JSON in canvasJS? - javascript

Im stuck at trying to get updated values from the JSON array and plotting it on canvasJS.
Here is my JSON array for sensor 1:
[{
"Date": "2020-01-24 07:35:46",
"sensorValue": 213
}, {
"Date": "2020-01-24 07:35:46",
"sensorValue": 433
}, {
"Date": "2020-02-10 06:03:36",
"sensorValue": 321
}, {
"Date": "2020-02-10 06:03:36",
"sensorValue": 43
}, {
"Date": "2020-02-12 03:30:57",
"sensorValue": 4321
}]
Below is my index2.php file
the updateChart function doesn't seem to work. Im not sure if this is the right way to do it.
the rationale behind the code: I wish to update the graph every few seconds with updated values retrieved thru php. if there are no updated values, the array should not change. hence the reason behind the for-loop and the date comparison.
<?php
include 'getsensor.php';
?>
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function() {
<?php
getSensor();
?>
var updateInterval = 2000;
var sensor1Data = <?php echo json_encode($json_sensor1, JSON_NUMERIC_CHECK); ?>;
var sensor2Data = <?php echo json_encode($json_sensor2, JSON_NUMERIC_CHECK); ?>;
// sensor datapoints
var sensor1 = [], sensor2 = [], sensor3 = [], sensor4 = [], sensor5 = [];
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled: true,
title: {
text: "Soil Moisture Reading"
},
axisX: {
title: "chart updates every " + updateInterval / 1000 + " secs"
},
axisY:{
includeZero: false
},
toolTip: {
shared: true
},
legend: {
cursor:"pointer",
verticalAlign: "top",
fontSize: 22,
fontColor: "dimGrey",
itemclick : toggleDataSeries
},
data: [{
type: "line",
name: "Sensor 1",
dataPoints: sensor1
},
{
type: "line",
name: "Sensor 2",
dataPoints: sensor2
}]
});
for(var i = 0; i < sensor1Data.length; i++) {
sensor1.push({
x: new Date(sensor1Data[i].Date),
y: Number(sensor1Data[i].sensorValue)
})
}
for(var i = 0; i < sensor2Data.length; i++) {
sensor2.push({
x: new Date(sensor2Data[i].Date),
y: Number(sensor2Data[i].sensorValue)
})
}
chart.render();
setInterval(function(){updateChart()}, updateInterval);
function toggleDataSeries(e) {
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else {
e.dataSeries.visible = true;
}
chart.render();
}
function updateChart() {
// retrieves new data from database. updates and shifts the graph.
<?php
getSensor();
?>
var sensor1DataNew = <?php echo json_encode($json_sensor1, JSON_NUMERIC_CHECK); ?>;
var i = sensor1DataNew.length - 1;
// retrieve the index of the new value
for (i; i > 0; i--){
if (sensor1DataNew[i].Date == sensor1Data[19].Date){
break;
}
}
// pushes the new values to be plotted
for(i; i < sensor1DataNew.length; i++) {
sensor1.push({
x: new Date(sensor1DataNew[i].Date),
y: Number(sensor1DataNew[i].sensorValue)
})
}
if(sensor1.length > 20){
sensor1.shift();
}
chart.render();
}
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
here is my getSensor.php file:
<?php
require_once 'mysqldb.php';
$json_sensor1 = array();
$json_sensor2 = array();
$json_sensor3 = array();
function getSensor(){
global $json_sensor1, $json_sensor2, $json_sensor3;
global $db_host, $db_user, $db_pass, $db_name;
/* start connection */
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
# get/display datetime and sensor value
$sensor1 = 'SELECT Date, sensorValue FROM sensor WHERE sensorName = "sensor 1" ORDER BY ID ASC, Date DESC LIMIT 20';
$sensor2 = 'SELECT Date, sensorValue FROM sensor WHERE sensorName = "sensor 2" ORDER BY ID ASC, Date DESC LIMIT 20';
$sensor3 = 'SELECT Date, sensorValue FROM sensor WHERE sensorName = "sensor 3" ORDER BY ID ASC, Date DESC LIMIT 20';
// $sensor3 = 'SELECT Date, sensorName, sensorValue FROM sensor WHERE Date IN (SELECT MAX(Date) FROM sensor WHERE sensorName = "sensor 3") ORDER BY ID ASC, Date DESC';
$json_sensor1 = sqlQuery($conn,$sensor1);
$json_sensor2 = sqlQuery($conn,$sensor2);
$json_sensor3 = sqlQuery($conn,$sensor3);
/* close connection */
mysqli_close($conn);
}
function sqlQuery($conn,$sql_query){
$json_array = array();
if($query = mysqli_query($conn,$sql_query)){
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$json_array[] = $row;
}
/* free result set */
mysqli_free_result($query);
}
return $json_array;
}
?>

I can't comment, but I think the problem lies in the way you load the data (or the lack of it).
Basically you are loading the data on the PHP page render once, and that is all.
You need some ajax requests periodically to load the data instead of the PHP echo in the updateChart method. (In the initialization part it is fine)
$.ajax({
type: "GET",
url: 'getSensorData.php',
dataType: "text",
async: false,
success: function(data){
sensor1DataNew = data;
}
});
Something like this might work (with a little jquery)

Related

Bar Chart.js doesn't show values with PHP, MySQL, AJAX

I'm using Chart.js plugin to create a bar chart with sales and purchases values by year. These values are stores in mysql database and I bring it via PHP/AJAX.
HTML
<canvas id="mybarChart"></canvas>
PHP
$sql = "SELECT YEAR(date) as years, SUM(amount) AS total FROM purchases GROUP BY YEAR(date)";
$res = mysql_query($sql);
$totalpurchases = [];
$sqll = "SELECT YEAR(date) as years, SUM(amount) AS total FROM sales GROUP BY YEAR(date)";
$ress = mysql_query($sqll);
$totalsales = [];
while($row = mysql_fetch_array($res)){
$totalpurchases[] = [$row['total']];
}
while($roww = mysql_fetch_array($ress)){
$totalsales[] = [$roww['total']];
}
echo json_encode(array($totalpurchases,$totalsales));
And I made my JS code like this:
function show_chartbar(lbl01,lbl02){
var ctx = document.getElementById("mybarChart");
var mybarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["2013", "2014", "2015", "2016", "2017"],
datasets: [{
label: '# Total Purchase',
backgroundColor: "#26B99A",
data: lbl01
}, {
label: '# Total Sales',
backgroundColor: "#03586A",
data: lbl02
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
if ($('#mybarChart').length ){
$.ajax({
url: "scripts/values.php",
type: "GET",
dataType: "json",
success: function(resp)
{
var totpurchases = resp[0];
var totsales = resp[1];
console.log("Total Purchases: "+totpurchases);
console.log("Total Sales: "+totsales);
show_chartbar(totpurchases,totsales);
}
});
}
In console it's showing values correctly but it doesn't display in the chart:
I tried to add additional brackets in data option but it's showing the same.
UPDATE
console.dir(resp);
How can I fix it? I'd like some help.
You are creating an Array of Arrays. I believe this will fix this issue.
while($row = mysql_fetch_array($res)){
$totalpurchases[] = $row['total'];
}
while($roww = mysql_fetch_array($ress)){
$totalsales[] = $roww['total'];
}

json works on localhost but not on server

I have the below part of code which works on my local machine but not on the server.
When I execute it on the server then am getting an error as "Uncaught SyntaxError: Unexpected token ;"
<?php
$checkValue = array();
$i= 0;
while ($row = mysql_fetch_array($searchdetails)) {
$checkValue[$i][] = $row['ID'];
$checkValue[$i][] = $row['1'];
$checkValue[$i][] = $row['2'];
$checkValue[$i][] = $row['3'];
if(#$row['4'] == "NULL" || #$row['4'] == NULL) {
$checkValue[$i][] = "NULL";
}else{
$sql = "SELECT * FROM Class WHERE ID_Class =".#$row['4'];
$data = mysql_query( $sql );
$class = mysql_fetch_assoc($data);
$checkValue[$i][] = $class['Class'];
}
if(#$row['5'] == "NULL" || #$row['5'] == NULL) {
$checkValue[$i][] = "NULL";
}else{
$sql = "SELECT * FROM Place WHERE ID_Place =".#$row['5'];
$data = mysql_query( $sql );
while($row1 = mysql_fetch_array($data)) {
$checkValue[$i][] = $row1['1'];
}
}
$i++;
}
?>
<script>
var grid;
var columns = [
{ id: "switch", name: "switch", field: "switch", formatter: imageFormatter, sortable: true },
{ id: "college", name: "college", field: "college", width: 50 },
{ id: "Number", name: "Number", field: "Number", width: 50 },
{ id: "Class", name: "Class", field: "Class",sortable: true },
{ id: "Place", name: "Place", field: "Place", width: 40 },
];
$(function () {
var MS_PER_DAY = 24 * 60 * 60 * 1000;
var data = [];
**var listdata = <?php echo json_encode($checkValue);?>;**
console.log(listdata);
for (var i = 0; i < listdata.length; i++) {
data[i] = {
switch: listdata[i][0],
college: listdata[i]['1'],
Number: listdata[i]['2'],
Strength: listdata[i]['3'],
Place: listdata[i]['4'],
};
}
})
</script>
I tried this after searching for different answers in Stackoverflow
var listdata = <?php echo json_encode($checkValue)?>;
but still it doesn't work.
What might be the issue thats stopping it here. Any help on this is much more appreciated!!
EDIT: I identified the reason, The table class has some Spanish characters in it and so it is not displaying the data. How to overcome with these characters?

Can't display highchart with my json data

I am using highchart to draw the graph, but there's a problem that I can't draw the graph when I tried to replace the URL of $.getJSON('URL', function (data)) to
$.getJSON('Highchart_getData.php', function (data) there's nothing displayed.
I choose this example
http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/stock/demo/flags-placement/
Then I want to connect my mysql data to draw the graph.
JS.javascript:
$.getJSON('Highchart_getData.php', function (data) {
var lastDate = data[data.length - 1][0], // Get year of last data point
days = 24 * 36e5; // Milliseconds in a day
// Create the chart
Highcharts.stockChart('container', {
rangeSelector: {
selected: 1
},
title: {
text: '光照量歷史圖表'
},
yAxis: {
title: {
text: '單位:Lux'
}
},
series: [{
name: '當日光照量',
data: data,
id: 'dataseries',
tooltip: {
valueDecimals: 4
}
}, {
type: 'flags',
name: 'Flags on series',
data: [{
x: lastDate - 60 * days,
title: 'On series'
}, {
x: lastDate - 30 * days,
title: 'On series'
}],
onSeries: 'dataseries',
shape: 'squarepin'
}, {
type: 'flags',
name: 'Flags on axis',
data: [{
x: lastDate - 45 * days,
title: 'On axis'
}, {
x: lastDate - 15 * days,
title: 'On axis'
}],
shape: 'squarepin'
}]
});
});
Highchart_getData.php:
<?php session_start(); ?>
<?php
$hostdb = "localhost";
$userdb = "root";
$passdb = "";
$namedb = "light_care";
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
include("mysql_connect.inc.php");
$id=$_SESSION['username'];
$today= date('Y')-2000;
$today .= date('-m-d');
$arrData = array();
if($_SESSION['username'] != null)
{
$sqlID = "select * from user where username='$id'";
$resultID = mysql_query($sqlID);
$userID=array();
if($resultID === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($resultID))
{
$userID[0]=$row["ID"];
}
for( $a=0;$a<30;$a++)
{
$date= date('Y')-2000;
$date .= date('-m-d',time()-24*60*60*$a);
//$date= date('Y-m-d',time()-24*60*60*$a);
$sql = "select * from data where user_id='$userID[0]' and data_time like
'%$date%'";
$result = mysql_query($sql);
$light=array();
//echo $date;
$count=0;
$light_sum=0;
$step_sum=0;
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$lsum=array();
$ssum=array();
$Data=0;
while($row = mysql_fetch_array($result))
{
$Date=$row["data_time"];
$Data+=$row["light"];
//$light_sum+=$Data[$count];
//$DATE=$Data[$count];
$count++;
}
//echo $date;
$date= date('Y');
$date .= date('-m-d',time()-24*60*60*$a);
$DATA[0]=$date;
$DATA[1]=$Data;
array_push($arrData,$DATA);
$light_sum=0;
}
/*JSON Encode the data to retrieve the string containing the
JSON representation of the data in the array. */
$jsonEncodedData = json_encode($arrData);
print($jsonEncodedData);
//Close the database connection
$dbhandle->close();
}
// }
?>
and the ouput is:
[["2017-07-20",0],["2017-07-19",0],["2017-07-18",562],["2017-07-17",746],["2017-07-16",0],["2017-07-15",0],["2017-07-14",0],["2017-07-13",0],["2017-07-12",0],["2017-07-11",0],["2017-07-10",0],["2017-07-09",0],["2017-07-08",0],["2017-07-07",0],["2017-07-06",0],["2017-07-05",0],["2017-07-04",0],["2017-07-03",0],["2017-07-02",0],["2017-07-01",0],["2017-06-30",0],["2017-06-29",0],["2017-06-28",0],["2017-06-27",0],["2017-06-26",0],["2017-06-25",0],["2017-06-24",0],["2017-06-23",0],["2017-06-22",0],["2017-06-21",0]]
JQ.html:
<!DOCTYPE html>
<html>
<script type="text/javascript" src="https://code.jquery.com/jquery-
3.1.1.min.js"></script>
<script type="text/javascript"
src="https://code.highcharts.com/stock/highstock.js"></script>
<script type="text/javascript"
src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<body>
<div id="container" style="height: 400px; min-width: 310px"></div>
</body>
<script type="text/javascript" src="JS.js"></script>
</html>
but there's nothing being displayed :(
I have struggle for many days, but it still can't work...
Is there anyone can help me .
Thank you very much! and sorry for my poor English.

How to pass nested foreach Values to CanvasJS chart?

I do some calculations with below Code and after that i want to pass the values to the Chart but i can not send them i have try this:
$getStoreIDs = mysqli_query($dbConnection, "SELECT DISTINCT Stores_storeID FROM maintable WHERE Survey_surveyId = '$surveyID' ");
while ($row = mysqli_fetch_array($getStoreIDs))
{
$storeIDarray[] = $row;
}
foreach($_POST['sections'] as $selected)
{
foreach ($storeIDarray as $key => $row)
{
$storeID = $row['Stores_storeID'];
$storeNames= mysqli_query($dbConnection , "SELECT storeName FROM stores WHERE storeID = '".$row['Stores_storeID']."'");
$sectinName = mysqli_query($dbConnection , "SELECT sectionName FROM sections WHERE sectionID = '$selected' ");
$totalSections = mysqli_query($dbConnection, "SELECT SUM(itemPrice) AS totalSection FROM maintable WHERE items_Family_Sections_sectionID='$selected' AND Stores_storeID = '$storeID' AND Survey_surveyId = '$surveyID' ");
}
}
i want to pass the values of ($storeNames, $ectionName and $totalSelections)
and here is my CanvasJs code `
var chart1 = new CanvasJS.Chart("chartContainer1",
{
title:{
text: "Store Comparision"
},
animationEnabled: true,
axisY: {
title: "Total Price"
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center"
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
dataPoints: [
]
}
]
});
chart1.render();`
First you need to put your javascript code before canvas chart,it renders.
How you are passing data to your view is important.Are you passing as json object or array?
If as json then need to parse in javscript before sending encoded in php.
In datapoints paraemeter you can pass like this
dataPoints: JSON.parse(<?php echo json_encode($json_managers) ?>)
Or can do via PHP before sending (A sample code snippet)
$managers = DB::table('orders')
->join('managers', 'orders.manager_id', '=', 'managers.id')
->groupBy('managers.manager_name')
->get(['managers.manager_name',DB::raw("sum(orders.sale) as sale")]);
foreach($managers as $key => $value){
$point = array("label" => $value->manager_name , "y" => $value->sale);
array_push($data_manager_points, $point);
}
$json_managers = json_encode($data_manager_points,JSON_NUMERIC_CHECK);
For more get here :
http://canvasjs.com/forums/topic/how-can-i-use-php-mysql-dynamic-data/

JSON Highcharts to draw multiple lines

I'm totally lost with Highcharts!. I have to draw a graph with multiple lines. I need a JSON output like this:
[{
"name": "2",
"data":
[1398333600000,1],[1398333600000,1],....
},
{
"name": "16",
"data":
[1398333600000,1],[1398333600000,1]...
},
{
....
....
}
]
...but, I get only a malformed JSON response from PHP file. ¿Some altruistic soul can enlighten the way? thank you very much in advance. Sorry, I am a super-newbie :(
My BD table Mysql:
i can´t upload a image with table BD on post, sorry! ...i need at least 10 reputation!
...link...
http://i57.tinypic.com/2efj43n.jpg
The javascript code:
chart = new Highcharts.Chart({
chart: {
renderTo: 'divStatsGrupo',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: titulo
},
tooltip: {
enabled: false,
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats : {
hour: '%H:%M',
labels: {
style: {
width: '200px','min-width': '100px'
},
useHTML : true
}
}
},
yAxis: {
categories: [ 'APAGADO', 'ACTIVO', 'ALARMA'],
title: {
text: 'ESTADO'
},
min: 0
},
series : [{
showInLegend: true,
name : data.name,
type : 'line',
data: data.data
}]
});
});
And the PHP code:
require_once('Connections/conexion.php');
$sesionUser = $_SESSION['MM_Username'];
$sesionIdGrupo = $_GET['idGrupo'];
$sesionFechaActual = $_GET['fechaActual'];
///ARREGLO FECHA RECIBIDA PARA ADAPTARLA A FORMATO DE LA BD YY-MM-DD
$sesionFechaActualArreglo = date_format(new DateTime($sesionFechaActual),"Y-m-d");
mysql_select_db($database_conexion, $conexion);
$query_RecordsetTabla = "SELECT * FROM registros WHERE idUsuario = (SELECT idUsuario FROM usuarios WHERE userName = '$sesionUser') AND idGrupo = '$sesionIdGrupo' AND fecha = '$sesionFechaActualArreglo'";
$RecordsetTabla = mysql_query($query_RecordsetTabla, $conexion) or die(mysql_error());
$totalRows_RecordsetTabla = mysql_num_rows($RecordsetTabla);
$arr = array();
while ($row_RecordsetTabla = mysql_fetch_assoc($RecordsetTabla))
{
$idDispositivo = $row_RecordsetTabla['idDispositivo'];
$fecha = $row_RecordsetTabla['fecha'];
$hora = $row_RecordsetTabla['hora'];
$estado = $row_RecordsetTabla['estado'];
$arregloFecha = date_format(new DateTime($fecha),"Y-m-d");
$arregloHora = date_format(new DateTime($hora),"H:i");
$arregloHora2 = strtotime($arregloHora) * 1000;
$arr[] = array($arregloHora2, floatval($estado));
$arrDisp[] = array(floatval($idDispositivo));
}
$arr2 = array('data' => $arr, 'name' => $arrDisp);
echo json_encode($arr2);
mysql_free_result($RecordsetTabla);
I recieve this from PHP file...
{"data":[[1398330000000,1],[1398332700000,1],[1398331800000,1],[1398332700000,1]],"name":[[2],[2],[16],[16]]}
I think I have problems with arrays, Gracias!
You're very close. I kept the code as similar to yours so you can see the minor differences.
$items = array();
while ($row_RecordsetTabla = mysql_fetch_assoc($RecordsetTabla))
{
$idDispositivo = $row_RecordsetTabla['idDispositivo'];
$fecha = $row_RecordsetTabla['fecha'];
$hora = $row_RecordsetTabla['hora'];
$estado = $row_RecordsetTabla['estado'];
$arregloFecha = date_format(new DateTime($fecha),"Y-m-d");
$arregloHora = date_format(new DateTime($hora),"H:i");
$arregloHora2 = strtotime($arregloHora) * 1000;
// changed $arr and $arrDisp to scalar
$arr = array($arregloHora2, floatval($estado));
$arrDisp = array(floatval($idDispositivo));
// name and data should be put as part of a single array
$items[] = array ( 'data' => $arr , 'name' => $arrDisp );
}
// $arr2 = array('data' => $arr, 'name' => $arrDisp);
echo json_encode($items);
mysql_free_result($RecordsetTabla);
Please note I wasn't able to test it out, but if it does not work, let me know and I'll look at it further.
In your json_encode, I advice to set JSON_NUMERIC_CHECK, then numbers will not be a strings.

Categories