Related
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)
I create tables using datatables, and data from MySQL. I want to add string data to data in my table, for example for data in columns the temperature of each data is (C) as shown below. How do I add strings like ° C and % to my table?
PHP code:
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "db_hosting");
//$columns = array('order_id', 'order_customer_name', 'order_item', 'order_value', 'order_date');
$columns = array('id', 'time', 'temperature', 'humidity');
$query = "SELECT id, DATE_FORMAT(time, '%d %M %Y %H:00') AS time, temperature, humidity FROM data WHERE ";
if($_POST["is_date_search"] == "yes")
{
$query .= 'DATE(time) BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
if(isset($_POST["search"]["value"]))
{
$query .= '
(id LIKE "%'.$_POST["search"]["value"].'%")
';
}
if(isset($_POST["order"]))
{
$query .= "GROUP BY DATE_FORMAT(time, '%d-%M-%Y %H:00') ORDER BY 'time'";
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query . $query1);
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = "";
$sub_array[] = $row["time"];
$sub_array[] = $row["temperature"];
$sub_array[] = $row["humidity"];
$data[] = $sub_array;
}
function get_all_data($connect)
{
$query = "SELECT * FROM data";
$result = mysqli_query($connect, $query);
return mysqli_num_rows($result);
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => get_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
?>
Table:
<table width="98%" class="table table-bordered table-striped" id="tabel_data" style="text-align:center;">
<thead >
<tr >
<th style="text-align:center;" width="8%">No.</th>
<th style="text-align:center;" width="22%">Datetime</th>
<th style="text-align:center;" width="18%">Temp (°C)</th>
<th style="text-align:center;" width="18%">Humidity (%)</th>
</tr>
</thead>
Javacript code (dataTable):
in javascript, there is a code to filter data based on date and can export table data
$(document).ready(function(){
$('.input-daterange').datepicker({
todayBtn:'linked',
format: "yyyy-mm-dd",
autoclose: true
});
fetch_data('no');
function fetch_data(is_date_search, start_date='', end_date='')
{
var dataTable = $('#tabel_data').DataTable({
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0,
} ],
"order": [[ 1, 'asc' ]],
dom: 'Bfrtip',
buttons: [
{
extend: 'print',
title: '<h3 align ="center">Data table</h3>',
text: '<i class="fa fa-l fa-print"></i> Print',
titleAttr: 'Cetak Tabel',
messageTop: '<p align ="center">created by PDFmake</p>',
filename: 'data_table'
},
{
extend: 'pdfHtml5',
customize: function (doc) {
doc.content[1].table.widths =
Array(doc.content[1].table.body[0].length + 1).join('*').split('');
doc.defaultStyle.alignment = 'center';
doc.styles.tableHeader.alignment = 'center';
doc.content.splice(0, 1, {
text: [{
text: 'Data Table \n',
bold: true,
fontSize: 16
}, {
text: ' Created by PDFmake \n', //
bold: true,
fontSize: 11
},],
margin: [0, 0, 0, 12],
alignment: 'center'
});
},
exportOptions: {
modifier: {
selected: null
}
},
title: 'Data table',
titleAttr: 'Simpan sebagai PDF',
text: '<i class="fa fa-l fa-file-pdf-o"></i> PDF',
filename: 'data_tabel_'
}
],
"paging": false,
"processing" : true,
"serverSide" : true,
bFilter:false,
"ajax" : {
url:"fetch.php",
type:"POST",
data:{
is_date_search:is_date_search, start_date:start_date, end_date:end_date
},
}
});
dataTable.on('draw.dt', function () {
var info = dataTable.page.info();
dataTable.column(0, { search: 'applied', order: 'applied', page: 'applied', }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1 + info.start;
dataTable.cell(cell).invalidate('dom');
});
});
}
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if(start_date != '' && end_date !='')
{
$('#tabel_data').DataTable().destroy();
fetch_data('yes', start_date, end_date);
//$("#tabel").show();
document.getElementById('tabel').style.display = "block";
}
else
{
alert("Both Date is Required");
}
});
});
you can create your table in JD by String:
String ="<th style="text-align:center;" width="18%">"+(variable)+"(°C)</th>"
You can wrap the content into <span>'s and do it in pure CSS:
Renderer:
columnDefs: [{
targets: [2,3],
render: function(data) {
return '<span>'+data+'</span>'
}
}]
CSS:
table.dataTable td:nth-child(3) span:after {
content: ' ℃';
color: red;
font-size: 80%;
}
table.dataTable td:nth-child(4) span:after {
content: ' %';
color: red;
font-size: 80%;
}
The benefit of this approach is that the data still is considered as numbers-
demo -> http://jsfiddle.net/1du07tfn/
I have a solution to the problem
PHP:
$data = array();
$celcius = ' °C';
$percent = ' %';
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = "";
$sub_array[] = $row["time"];
$sub_array[] = $row["temperature"].$celcius;
$sub_array[] = $row["humidity"].$percent;
$data[] = $sub_array;
}
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.
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.
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.