나의 코드 입니다..
<script>
var dataTable;
$(document).ready(function(){
// Initialize datatable
dataTable = $('#empTable').DataTable({
dom: 'Blfirtp',
"lengthMenu": [
[10, 50, 100, 500, '-1'],
[10, 50, 100, 500, "All"]
],
'buttons': [
{
extend: 'csv',
exportOptions: {
columns: [1,2,3,4,5]
}
},
{
extend: 'excel',
exportOptions: {
columns: [1,2,3,4,5]
}
}
],
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'ajax': {
'url':'ajaxfile.php',
'data': function(data){
// Read values
data.request = 1;
}
},
'columns': [
{ data: 'action' },
{ data: 'emp_name' },
{ data: 'email' },
{ data: 'gender' },
{ data: 'salary' },
{ data: 'city' }
],
'columnDefs': [ {
'targets': [0], // column index (start from 0)
'orderable': false, // set orderable false for selected columns
}]
});
// Check all
$('#checkall').click(function(){
if($(this).is(':checked')){
$('.delete_check').prop('checked', true);
}else{
$('.delete_check').prop('checked', false);
}
});
// Delete record
$('#delete_record').click(function(){
var deleteids_arr = [];
// Read all checked checkboxes
$("input:checkbox[class=delete_check]:checked").each(function () {
deleteids_arr.push($(this).val());
});
// Check checkbox checked or not
if(deleteids_arr.length > 0){
// Confirm alert
var confirmdelete = confirm("Do you really want to Delete records?");
if (confirmdelete == true) {
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 2,deleteids_arr: deleteids_arr},
success: function(response){
dataTable.ajax.reload();
}
});
$('#checkall').prop('checked', false);
}
}
});
});
// Checkbox checked
function checkcheckbox(){
// Total checkboxes
var length = $('.delete_check').length;
// Total checked checkboxes
var totalchecked = 0;
$('.delete_check').each(function(){
if($(this).is(':checked')){
totalchecked+=1;
}
});
// Checked unchecked checkbox
if(totalchecked == length){
$("#checkall").prop('checked', true);
}else{
$('#checkall').prop('checked', false);
}
}
</script>
</body>
</html>
Datatables, There is no problem when writing the initial function, but when it is added more and more, if you suddenly select all, not work
Hi there,
i have a table with over 8.000 entries (until now, data will rise in future). In some cases i have to export all of them to Excel, therefor i set the lengthMenu to:
Plain text
"lengthMenu": [[10, 25, 50, 250, -1], [10, 25, 50, 250, "All"]],
It works fine until i use the "All" statement. With "All" i get the following error:
Unable to get property 'length' of undefined or null reference
Can anybody help me? Normally it makes no sense to show all 8.000 entries on the webpage, but i have to export them all to Excel. Perhaps someone knows a better way.
이것은 ajaxfile.php
<?php
include 'config.php';
$request = $_POST['request'];
// Datatable data
if($request == 1){
## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = mysqli_real_escape_string($con,$_POST['search']['value']); // Search value
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery .= " and (emp_name like '%".$searchValue."%' or
email like '%".$searchValue."%' or
city like'%".$searchValue."%' ) ";
}
## Total number of records without filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];
## Total number of records with filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];
## Fetch records
$empQuery = "select * from employee WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = mysqli_query($con, $empQuery);
$data = array();
while ($row = mysqli_fetch_assoc($empRecords)) {
$data[] = array(
"action"=>"<input type='checkbox' class='delete_check' id='delcheck_".$row['id']."' onclick='checkcheckbox();' value='".$row['id']."'>",
"emp_name"=>$row['emp_name'],
"email"=>$row['email'],
"gender"=>$row['gender'],
"salary"=>$row['salary'],
"city"=>$row['city'],
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data,
);
echo json_encode($response);
exit;
}
// Delete record
if($request == 2){
$deleteids_arr = $_POST['deleteids_arr'];
foreach($deleteids_arr as $deleteid){
mysqli_query($con,"DELETE FROM employee WHERE id=".$deleteid);
}
echo 1;
exit;
}
?>
Related
I'm currently working on a condominum program. The goal of this issue is when one Apartment row is clicked on the Parent table all the months - related to that apartment - must be displayed on the Child table.
The click/select/deselect is working fine but I can not obtain all the twelfth months.
This is my actual tables layout (example 1):
And this is my actual tables layout (example 2):
My code to childTable is:
var childTable = $('#child').DataTable( {
"pageLength": 12,
ajax: {
url: "ajax/query_pagquotas.php", // This is the URL to the server script for the child data
dataSrc: function (data) {
var selected = parentTable.row( { selected: true } );
if ( selected.any() ) {
var ID = selected.data().ID;
for (var i=0; i < data.data.length; i++) {
var rows = data.data[i];
if (rows.ID === ID) {
return [rows];
}
}
} else {
return [];
}
}
},
columns: [
{ "data": "ID" },
{ "data": "DATA" },
{ "data": "MES" },
{ "data": "VALOR" },
{ "data": "METODO" },
{ "data": "ESTADO" },
{ "data": "OBS" }
]
} );
Thanks for your help Masters
[edited]
Ups! If condition at the end does not make the 'deselect' work...
This is my full code at the moment:
$(document).ready(function() {
var parentTable = $('#parent').DataTable( {
ajax: "ajax/dbfraccoes.php",
"language": {
"sSearchPlaceholder": "Apto ou Proprietário...",
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Portuguese.json",
},
"processing": true,
"scrollY": "200px",
"scrollCollapse": true,
"paging": false,
pageLength: 5,
select: {
style: 'single'
},
columns: [
{ "data": "ID","searchable": false },
{ "data": "APTO" },
{ "data": "FRACCAO"},
{ "data": "PROPRIETARIO" },
{ "data": "VALOR_QUOTA","searchable": false, className: "cssValores"},
{ "data": "OBS" }
]
} );
// tabela Child ------------------------------------------
var childTable = $('#child').DataTable( {
columnDefs: [{
targets: 6,
render: function(data, type, row, meta){
if(type === 'display' && data === 'EMITIDO'){
data = '<td style="text-align:center"><button type="button" class="btn btn-info btn-sm cssButton center" title="Emitido Aviso de Recibo a pagamento">EMITIDO</button></td>'+
'<div class="links">' +
'Editar ' +
'</div>';
}else if (type === 'display' && data === 'AGUARDA'){
data = '<td style="text-align:center"><button type="button" class="btn btn-warning btn-sm cssButton center" title="Limite de pagamento ultrapassado. Em período de tolerância.">AGUARDA</button></td>'+
'<div class="links">' +
'<a href="<?php echo WEB_URL;?>credit_debit/gest_quotas.php?spid='+
row['pqid']+'#insert">Editar</a> ' +
'</div>';
}
return data;
}
}],
"paging": false,
"searching": false,
"language": {
"zeroRecords": "<center>Clique na tabela acima, na linha do apartamento que pretende. <br/>Os dados da fracção/apartamento selecionado acima serão reflectidos nesta tabela</center>",
},
ajax: {
url: "ajax/query_pagquotas.php",
dataSrc: function (data) {
var selected = parentTable.row( { selected: true } );
if ( selected.any() ) {
var rows = []; // create an empty array
var ID = selected.data().ID;
for (var i=0; i < data.data.length; i++) {
var row = data.data[i];
if (row.ID === ID) {
rows.push(row);
}
}
}
return rows;
},
},
columns: [
{ "data": "pqid" },
{ "data": "ID"},
{ "data": "DATA" },
{ "data": "MES"},
{ "data": "VALOR", className: "cssValores"},
{ "data": "METODO" },
{ "data": "ESTADO" },
{ "data": "OBS" }
]
} );
// This will load the child table with the corresponding data
parentTable.on( 'select', function () {
childTable.ajax.reload();
} );
//clear the child table
parentTable.on( 'deselect', function () {
childTable.ajax.reload();
} );
} );
The simplest way to adjust your existing code, is to change the logic in your dataSrc: function (data) {...}.
At the moment, you are only creating an array of one item.
So, instead you can do this:
dataSrc: function (data) {
var selected = parentTable.row( { selected: true } );
var rows = []; // create an empty array
if ( selected.any() ) {
var ID = selected.data().ID;
for (var i=0; i < data.data.length; i++) {
var row = data.data[i]; // change the variable name to "row"
if (row.ID === ID) {
rows.push(row); // add the new row to your array of rows
}
}
}
return rows; // return your array of rows
}
The most important line here is: rows.push(row); which is how JavaScript adds a new item to the end of an array.
So, now at the end of your dataSrc function you will either have an empty array [] if no rows were selected, or you will have an array of rows which match your ID.
That should solve your current problem.
The above approach should work - but it involves fetching every child row, every time - and then filtering out the ones you do not want to show.
You can probably improve on this by submitting the ID of the selected row as part of the child table's ajax URL. You can move the relevant code from its current location into your parentTable's on(select) function:
var selectedID = -1
parentTable.on( 'select', function () {
var selected = parentTable.row( { selected: true } );
if ( selected.any() ) {
selectedID = selected.data().ID;
}
childTable.ajax.reload();
} );
I do not know how you have implemented your ajax/query_pagquotas.php, so I am not sure of the best way to pass the selectedID parameter to it.
Normally I would append it as a query parameter in your ajax parameters:
data: 'id=' + selectedID
You may already know how to do this yourself.
Once you have passed the selectedID to your PHP, then you can use it to return only the records you want to display - and you can remove all of the existing dataSrc: function (data) {...} logic from your child table definition.
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'm working with Datatables server-side processing in OctoberCMS.
Everything works fine but search input doesn't work.
Search input works fine as I tried it in client-side processing.
Datatables part Javascript
$(document).ready(function() {
var tableId = "datalist";
var table = $('#' + tableId).DataTable({
processing: true,
serverSide: true,
ajax: {
url: '/ajax?tb={{ tableName|raw() }}&fd={{ fields|raw() }}',
type: 'GET',
//tb: 'BYAPPS_apps_data',
error: function(e) {
console.log(e);
}
},
paging: true,
pageLength: 50,
"info": false,
"autoWidth": true,
"fixedHeader": false,
"responsive": true,
"orderClasses": false,
"stateSave": true,
"dom": 'Bfrtip',
"buttons": [
'excel', 'copy'
],
});
$('.dataTables_filter input').bind('keyup', function () {
console.log('here');
table.search(this.value).draw();
});
});
Ajax part PHP file
function onStart()
{
$table = $_GET['tb'];
$length = $_GET['length'];
$start = $_GET['start'];
$fields = explode("|", $_GET['fd']);
$result = DB::table($table)->skip($start)->limit($length)->get();
$data = array();
foreach($result as $row) {
$sub_array = array();
for ($i = 0; $i < count($fields); $i++) {
$sub_array[] = $row->{$fields[$i]};
}
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_GET['draw']),
"recordsTotal" => DB::table($table)->count(),
"recordsFiltered" => DB::table($table)->count(),
"data" => $data,
);
echo json_encode($output);
}
How can I fix this and make the search input work?
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.