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.
Related
나의 코드 입니다..
<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;
}
?>
I've got an ajax call that get dynamic data and places them in select2 as follow :
$.ajax({
type: 'get',
url: '/api/?stuff='+c,
dataType: "json",
success: function (response) {
// If select2 is already defined, we destroy it and rebuild it with the new data
if(typeof $(".select2edit").data('select2') !== 'undefined') {
$(".select2edit").select2('destroy').select2({ data: response, width: '100%', closeOnSelect: false });
} else {
$(".select2edit").select2({ data: response, width: '100%', closeOnSelect: false });
}
}
});
I create the response using PHP and then transform it to JSON before sending it :
$old_emplacement = '';
$results = array();
$i = -1;
while($array_campaign = tep_db_fetch_array($campaign)){
if ($array_campaign['name'] != $old_emplacement) {
$i++;
$results['results'][$i]['text'] = $array_campaign['name'];
$old_emplacement = $array_campaign['name'];
$c = 0;
}
$results['results'][$i]['children'][$c]['id'] = $array_campaign['id'];
$results['results'][$i]['children'][$c]['text'] = $array_campaign['c_name'];
$c++;
}
$results['pagination']["more"] = true;
Thus resulting in the following JSON format :
{
"results": [
{
"text": "Name 1",
"children" : [
{
"id": 1,
"text": "Text 1.1"
},
{
"id": 2,
"text": "Text 1.2"
}
]
},
{
"text": "Name 2",
"children" : [
{
"id": 1,
"text": "Text 2.1"
},
{
"id": 2,
"text": "Text 2.2"
}
]
}
],
"paginate": {
"more": true
}
}
I get a No results found. when select2 initializes and loads. And I have no idea why. It's the correct format as far as the documentation is saying and other questions seem to confirm. Any ideas where could the problem be coming from?
It's also good to note that my select2 is inside a form which is inside a modal, and this is it's html :
<select name="xx[]" id="edit-xx" name='xx' class="form-control select2edit" multiple>
</select>
The problem was with the format generated by my PHP code. I'm posting the result here for anyone trying to generate a select2 optgroup format using PHP and for my own reference :
$old_emplacement = '';
$results = array();
$i = -1;
while($array_campaign = tep_db_fetch_array($campaign)){
if ($array_campaign['name'] != $old_emplacement) {
$i++;
$results[$i]['text'] = $array_campaign['name'];
$old_emplacement = $array_campaign['name'];
$c = 0;
}
$results[$i]['children'][$c]['id'] = $array_campaign['id'];
$results[$i]['children'][$c]['text'] = $array_campaign['c_name'];
if(in_array($array_campaign['id'], $campaigns_array)) {
$results[$i]['children'][$c]['selected'] = true;
}
$c++;
}
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?
I have a Javascript file with a function I'm trying to test. All the function does is make a jQuery post request to a PHP ajax file (see code)
function loadTeams(clubID){
var data = {
action: 'loadClubTeams',
clubID: clubID
};
return jQuery.post('/ajax/calendar_ajax.php', data);
}
I have a mock set up in my /__mocks__/ dir as such:
<?php
$teams = array(
array(
"Name" => "Team 1",
"ClubID" => 34
),
array(
"Name" => "Team 2",
"ClubID" => 34
),
array(
"Name" => "Team 3",
"ClubID" => 35
)
);
$response = array();
if($_REQUEST['action'] == "loadClubTeams"){
foreach($teams as $team){
if($team['ClubID'] == $_REQUEST['ClubID']){
array_push($response, $team);
}
}
}
return json_encode($response);
Here is my test file:
const assoc_cal = require('../../secure-htdocs/js/templates/association_calendar');
jest.mock('../../secure-htdocs/ajax/calendar_ajax.php');
test("loadTeams returns Teams 1 and 2 when passed clubID 34", () =>{
data = {action: "loadTeams", ClubID: 34};
const expected = [
{
name: "Team 1",
clubID: 34
},
{
name: "Team 2",
clubID: 34
}
];
expect(assoc_cal(data)).toEqual(expect.arrayContaining(expected));
});
But when I run my test, it still tries to call the real calendar_ajax.php file. I'm apparently setting up the mock incorrectly. Can anyone else out with this?
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.