JSON Highcharts to draw multiple lines - javascript

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.

Related

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

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)

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'];
}

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/

ext JS Grid text area json syntax error

i have project to show a text area inside the extjs grid panel. the form success full become text area and save to database. but when i load the value from database it shown syntax error
in google console shown error like this
Ext.data.JsonP.callback8({"totalItems": 2,"items": [{ "no": "1","kegiatan": "Target 12345 - 5432
asd
asd
asd
", "target": "harus sesuai target" },{ "no": "2","kegiatan": "Target 12 revisi error lagi", "target": "78.00" }]});
here the form created by request_form.js
function test(v){
return v === undefined || v === null ? '' : v.replace(/\n/g, '<br>');
}
.......
xtype: 'gridpanel',
id: 'frm_request_form_gridpanel',
title: 'Rencana Target dan Pencapaian Kerja',
width: 750,
height: 300,
border: 1,
margin: '10 5 10 10',
store: Ext.data.StoreManager.lookup('DetailTargetStore'),
columns: [
{header:'No', dataIndex: 'no', width: 40},
{header:'Jenis Kegiatan', dataIndex: 'kegiatan',
width: 350,
//type: 'textarea',
//grow:true,
//renderer:columnWrap
// field: {type: 'textarea',maxLength: 1024,renderer:columnWrap,grow:true}
renderer:test,
editor:'textarea',
flex: 1
....
handler: function(){
var dataObj = [];
var dataEmployee = EmployeReqStore.data.items;
var editedRecords = DetailTargetStore.getModifiedRecords();
for (var i=0; i<editedRecords.length; i++) {
dataObj.push(
{
tag_id:'edited',
emp_id:Ext.getCmp('nik').getValue(),
periode: Ext.getCmp('frm_request_form-periode').getValue(),
ccgroup : dataEmployee[0].data.ccgroup_id,
costcenter : dataEmployee[0].data.costcenter_id,
location : dataEmployee[0].data.location_id,
targetno: editedRecords[i].data.no,
targetket: editedRecords[i].data.kegiatan,
targetnilai: editedRecords[i].data.target,
//targettipe: editedRecords[i].data.target_tipe,
status: 'DRAFT'
}
);
}
.....
id: 'SubmitBtn',
text: 'Submit',
handler: function(){
var dataObj = [];
var dataEmployee = EmployeReqStore.data.items;
var editedRecords = DetailTargetStore.getModifiedRecords();
for (var i=0; i<editedRecords.length; i++) {
dataObj.push(
{
tag_id:'edited',
emp_id:Ext.getCmp('nik').getValue(),
periode: Ext.getCmp('frm_request_form-periode').getValue(),
ccgroup : dataEmployee[0].data.ccgroup_id,
costcenter : dataEmployee[0].data.costcenter_id,
location : dataEmployee[0].data.location_id,
targetno: editedRecords[i].data.no,
targetket: editedRecords[i].data.kegiatan,
targetnilai: editedRecords[i].data.target,
//targettipe: editedRecords[i].data.target_tipe,
status: 'NEW'
}
);
}
here save php with json object
foreach ($dataObj as $object) {
...
$stmtupdt = $db->prepare($sqlupdt);
$stmtupdt->execute(array(
':docno_id' => $doc_no,
':target_ket' => $object->targetket,
//':target_tipe' => $object->targettipe,
':target_nilai' => $object->targetnilai,
':target_no' => $object->targetno,
':target_status' => $object->status,
':periode_id' => $object->periode)
...
here load php with json object
$result = mysql_query($sql);
$totalitem = mysql_num_rows($result);
$count = 0;
echo '"totalItems": ' . $totalitem. ',';
echo '"items": [';
if ($result) {
if ($totalitem>0){
while($row = mysql_fetch_array($result)){
if(++$count == $totalitem) {
echo '{ "no": "'.$row['target_no'].'","kegiatan": "'. htmlentities($row['target_ket']).'", "target": "'.$row['target_nilai'].'" }';
}
else {
echo '{ "no": "'.$row['target_no'].'","kegiatan": "'. htmlentities($row['target_ket']).'", "target": "'.$row['target_nilai'].'" },';
}
}
i assume it some problem with json passing object but i dont know how to fix the json. please give me solution
thank you
Build a PHP array, and use json_encode:
$items = array();
while ($row = mysql_fetch_array($result)) {
$items[] = array(
'no' => $row['target_no'],
'kegiatan' => htmlentities($row['target_ket']),
'target' => $row['target_nilai'],
);
}
echo json_encode(array(
'totalItems' => $totalItems,
'item' => $items,
));
The error message Uncaught SyntaxError: Unexpected token ILLEGAL means usually a string that isn't closed on the same line, or in other words an unescaped new line in a string.

Highcharts json php multiple series

I have a simple question but for some reason can't find the solution. As described here: highcharts documentation, I made the following script:
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column',
},
title: {
text: 'Dagelijks waterverbruik'
},
subtitle: {
text: 'Waterverbruik in liters'
},
xAxis: {
categories: [
'Zondag',
'Maanag',
'Dinsdag',
'Woensdag',
'Donderdag',
'Vrijdag',
'Zaterdag'
]
},
yAxis: {
min: 0,
title: {
text: 'Waterverbruik (Liter)'
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{}]
};
$.getJSON('testdata.php', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>
my testdata.php is as follows:
<?php
header('Content-Type: application/json');
$data[] = array('Zondag',11);
$data[] = array('Maandag',10);
$data[] = array('Dinsdag',9);
$data[] = array('Woensdag',8);
$data[] = array('Donderdag',12);
$data[] = array('Vrijdag',2);
$data[] = array('Zaterdag',18);
$serie1[] = array('name' => 'serie 1', 'data' => $data);
$serie1[] = array('name' => 'serie 2', 'data' => $data);
echo json_encode($serie1);
?>
For some reason the charts don't render. What am I doing wrong? One series is working this way, but multiple series don't.
As you can see I would expect two bars with the same value. The output of testdata.php is:
[{"name":"serie 1","data":[["Zondag",11],["Maandag",10],["Dinsdag",9],["Woensdag",8],["Donderdag",12],["Vrijdag",2],["Zaterdag",18]]},{"name":"serie 2","data":[["Zondag",11],["Maandag",10],["Dinsdag",9],["Woensdag",8],["Donderdag",12],["Vrijdag",2],["Zaterdag",18]]}]
You make the array like this and do not use categories in the $data array because you are using static categories in chart.following is a hint
$data = array(11,10,9,8,12,81);
$serie1[] = array('name' => 'serie 1', 'data' => $data);
$serie1[] = array('name' => 'serie 2', 'data' => $data);
echo json_encode($serie1);
In this part:
$.getJSON('testdata.php', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
Change it to this
$.getJSON('testdata.php', function(data) {
options.series = data;
var chart = new Highcharts.Chart(options);
});
You current code can only accomodate one series since you specified an index to the series i.e. [0].
In the JSON you need to set JSON_NUMERIC_CHECK flag, because in your example it seems that you have no numebr values on data.

Categories