I want to create a cascade dropdown on jTable using PHP on the server side. I've been following the demo provided in the API, but despite my efforts I don't seem to get it working. Using firebug I found out the AJAX request to fill the second dropdown is not being made. Anyway, here's part of the code I have. Hope you can throw some light on this.
The first dropdown is called "Region" and the second one "Trabajo", depending on the Region I want to pull from the database the workplaces that belong to it.
<script type="text/javascript">
$(document).ready(function () {
//Prepare jTable
$('#PeopleTableContainer').jtable({
title: 'Colaboradores',
paging: true,
sorting: true,
defaultSorting: 'no_empleado ASC',
actions: {
listAction: 'usuariosActions.php?action=list',
createAction: 'PersonActionsPagedSorted.php?action=create',
updateAction: 'PersonActionsPagedSorted.php?action=update'
},
fields: {
no_empleado: {
title: 'Numero de colaborador',
key: true,
edit: false,
},
nombres: {
title: 'Nombres',
},
apellido_paterno: {
title: 'Apellido paterno',
},
apellido_materno: {
title: 'Apellido materno',
},
genero: {
title: 'Genero',
type: 'radiobutton',
options:{'0':'FEMENINO','1':'MASCULINO'},
list:false
},
fecha_nacimiento: {
title: 'Fecha de nacimiento',
type: 'date',
displayFormat: 'yy-mm-dd',
list:false
},
estado_civil: {
title: 'Estado civil',
options:{ '-1':'','1': 'CASADO', '2': 'DIVORCIADO', '3': 'SOLTERO','4':'UNION LIBRE','5':'VIUDO' },
list:false
},
dependientes: {
title: 'Número de dependientes',
options:{ '-1':'','0':'0','1': '1', '2': '2', '3': '3','4':'4','5':'5','6':'6','7':'7','8':'8','9':'9','10':'10','11':'11','12':'12','13':'13','14':'14','15':'15','16':'16','17':'17','18':'18','19':'19','20':'20' },
list:false
},
seguro_social: {
title: 'Número de seguridad social',
list:false
},
RFC: {
title: 'RFC',
list:false
},
calle: {
title: 'Calle',
list:false
},
no_ext: {
title: 'No. Ext',
list:false
},
no_int: {
title: 'No. Int',
list:false
},
colonia: {
title: 'Colonia',
list:false
},
mun_del: {
title: 'Del/Mun',
list:false
},
zip: {
title: 'Zip',
list:false
},
telefono: {
title: 'Telefono',
list:false
},
entidad_federativa: {
title: 'Entidad federativa',
list:false
},
fecha_antiguedad: {
title: 'Fecha ingreso',
type: 'date',
displayFormat: 'yy-mm-dd',
list:false
},
fecha_puesto: {
title: 'Fecha de inicio en el puesto',
type: 'date',
displayFormat: 'yy-mm-dd',
list:false
},
escolaridad: {
title: 'Escolaridad',
options:{ '-1':'','1': 'PRIMARIA', '2': 'SECUNDARIA', '3': 'PREPARATORIA','4':'UNIVERSIDAD','5':'ESPECIALIDAD','6':'POSGRADO','7':'MAESTRIA' },
list:false
},
puesto: {
title: 'Puesto',
list:false
},
contrato: {
title: 'Contrato',
options: {'-1':'','1':'Contrato por Tiempo Indeterminado','2':'Contrato por Tiempo Determinado','3':'Contrato por Obra Determinada','4':'Contrato por Tiempo Determinado'},
list:false
},
ocupacion:{
title: 'Ocupacion',
type: 'textarea',
list:false
},
region: {
title: 'Región',
options: 'usuariosActions.php?action=region',
list:false
},
trabajo: {
title: 'Centro de trabajo',
dependsOn: 'region',
options: function(data){
if(data.source == 'list'){
return 'usuariosActions.php?action=workplaces®ion=0';
}
return 'usuariosActions.php?action=workplaces®ion=' + data.dependedValues.region;
},
list:false
}
}
});
$('#LoadRecordsButton').click(function (e) {
e.preventDefault();
$('#PeopleTableContainer').jtable('load', {
no_empleado: $('#no_empleado').val()
});
});
//Load person list from server
$('#LoadRecordsButton').click();
});
</script>
And here's the PHP code
<?php
require_once("dbconnect.php");
if($_GET["action"] == "list")
{
//Get record count
if(isset($_POST['no_empleado']) && $_POST['no_empleado'] != ""){
$sql_result = 'SELECT
c.`no_empleado`,
c.`nombres`,
c.`apellido_paterno`,
c.`apellido_materno`,
c.`fecha_nacimiento`,
c.`fecha_antiguedad`,
c.`fecha_puesto`,
c.`estado_civil`,
c.`dependientes`,
c.`seguro_social`,
C.`escolaridad`,
C.`puesto`,
C.`RFC`,
C.`genero`,
C.`contrato`,
C.`ocupacion`,
C.`calle`,
C.`no_int`,
C.`no_ext`,
C.`colonia`,
C.`zip`,
C.`mun_del`,
C.`telefono`,
C.`entidad_federativa`,
c.`id_workplace` as trabajo,
r.`id_region` as region
FROM `colaboradores` AS c
INNER JOIN `workplaces` AS w
ON w.`id_workplace` = c.`id_workplace`
INNER JOIN `regiones` AS r
ON r.`id_region` = w.`id_region`
WHERE `no_empleado`= '.$_POST["no_empleado"].';';
$sql_count = 'SELECT COUNT(*) AS RecordCount FROM `colaboradores` WHERE `no_empleado`= '.$_POST["no_empleado"].';';
}
else{
$sql_result = 'SELECT
c.`no_empleado`,
c.`nombres`,
c.`apellido_paterno`,
c.`apellido_materno`,
c.`fecha_nacimiento`,
c.`fecha_antiguedad`,
c.`fecha_puesto`,
c.`estado_civil`,
c.`dependientes`,
c.`seguro_social`,
C.`escolaridad`,
C.`puesto`,
C.`RFC`,
C.`genero`,
C.`contrato`,
C.`ocupacion`,
C.`calle`,
C.`no_int`,
C.`no_ext`,
C.`colonia`,
C.`zip`,
C.`mun_del`,
C.`telefono`,
C.`entidad_federativa`,
r.`id_region` as region,
c.`id_workplace` as trabajo
FROM `colaboradores` AS c
INNER JOIN `workplaces` AS w
ON w.`id_workplace` = c.`id_workplace`
INNER JOIN `regiones` AS r
ON r.`id_region` = w.`id_region`
ORDER BY ' . $_GET["jtSorting"] . ' LIMIT ' . $_GET["jtStartIndex"] . ',' . $_GET["jtPageSize"] . ';';
$sql_count = 'SELECT COUNT(*) AS RecordCount FROM `colaboradores`';
}
$result = $mysqli->query($sql_count);
$row = $result->fetch_assoc();
$recordCount = $row['RecordCount'];
//Get records from database
$result = $mysqli->query($sql_result);
//Add all records to an array
$rows = array();
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['TotalRecordCount'] = $recordCount;
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
}
if($_GET["action"] == "region"){
$sql_count = 'SELECT `id_region` as Value ,`nombre_region` as DisplayText FROM `regiones`;';
$result = $mysqli->query($sql_count);
$rows = array();
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
//Get records from database
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Options'] = $rows;
print json_encode($jTableResult);
}
if($_GET["action"] == "workplaces"){
$region=$_GET['region'];
if ($region == "")
$result = $mysqli->query("SELECT `id_workplace` as Value, `nombre_workplace` as DisplayText FROM `workplaces` ");
else
$result = $mysqli->query("SELECT `id_workplace` as Value, `nombre_workplace` as DisplayText FROM `workplaces` WHERE `id_region` = '".$region."'");
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Options'] = $rows;
print json_encode($jTableResult);
}
I was right, dependsOn was not sending any sort of event signal and therefore the ajax call wasn't being made. I was using the min.js that came with the zip but it wasn't the newest version, 2.4.0, it was 2.2.0. it seems this functionality was not implemented yet on that version or was buggy.
Anyway, stick to version 2.4.0 and make sure to take a look into the js version if you run into trouble.
Related
new to this and (almost) desperate. in below code i want to set $rows1['date'][] = $data['tanggal']; data as X-Axis in highchart :
$(function () {
var chart;
$(document).ready(function() {
getAjaxData(1);
var val = location.search.split('proyek=')[1]
getAjaxData(val);
function getAjaxData(proyek){
$.getJSON("src/json/data.php", {proyek: proyek}, function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'scurve-proyek',
type: 'column'
},
title: {
text: ''
},
credits: {
enabled: false,
},
subtitle: {
text: ''
},
yAxis: {
min: 0,
max: 100,
tickInterval: 20,
title: {
text: ''
},
},
xAxis: {
type: 'datetime',
labels: {
formatter: function ( ){
return Highcharts.dateFormat('%Y-%m-%d', this.value);
},
},
},
tooltip:{
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.numberFormat(this.y, 2) +' %';
},
},
plotOptions: {
column: {
dataLabels: {
enabled: true,
format: '{point.y:,.2f}'+'%',
}
},
},
series: json
});
});
};
});
});
my data.php :
<?php
header("Content-type: application/json");
require_once "database.php";
$db = new database();
$mysqli = $db->connect();
$proyek = $_GET['proyek'];
$sql = "SELECT fren_pr FROM data_proyek WHERE kode_proyek = '$proyek'";
$rows = array();
$rows['name'] = 'Rencana';
$rows['color'] = '#50B432';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$rows['data'][] = array($data['fren_pr'],);
}
$sql = "SELECT freal_pr, tanggal FROM data_proyek WHERE kode_proyek = '$proyek'";
$rows1 = array();
$rows1['name'] = 'Realisasi';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$rows1['data'][] = $data['freal_pr'];
$rows1['date'][] = $data['tanggal'];
}
$rslt = array();
array_push($rslt, $rows);
array_push($rslt, $rows1);
print json_encode($rslt, JSON_NUMERIC_CHECK);
$mysqli->close();
this is my json view :
I've spent a lot of time trying to solve it but haven't found a solution until now.
Is there an error in my php code?
hope someone will be kind enough to help, Thanks in advance.
I'm trying to display a line chart with json data, but with there, $_GET from the json I have the chart doesn't appear, here's my code :
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("master/proyek/s-curve.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'scurve',
type: 'line'
},
credits: {
enabled: false
},
title: {
text: 'S-Curve Balai'
},
subtitle: {
text: ''
},
xAxis: {
categories: ['M1', 'M2', 'M3', 'M4']
},
yAxis: {
title: {
text: ''
},
plotLines: [{
value: 1,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'horizontal',
},
plotOptions: {
line: {
dataLabels: {
enabled: true,
distance: 100,
}
}
},
series: json,
});
});
});
});
and this my s-curve.php :
<?php
header("Content-type: application/json");
require_once "config/database.php";
$db = new database();
$mysqli = $db->connect();
$balai = mysqli_real_escape_string($mysqli, $_GET['balai']);
if ($balai == 'bl-1') {
$sql = "SELECT plan, actual FROM scurve1 ORDER BY id ASC";
} else if ($balai == 'bl-2') {
$sql = "SELECT plan, actual FROM scurve2 ORDER BY id ASC";
} else if ($balai == 'bl-3') {
$sql = "SELECT plan, actual FROM scurve3 ORDER BY id ASC";
}
$hasil = array();
$hasil['name'] = 'Plan';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$hasil['data'][] = $data['plan'];
}
$hasil1 = array();
$hasil1['name'] = 'Actual';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$hasil1['data'][] = $data['actual'];
}
$nilai = array();
array_push($nilai, $hasil);
array_push($nilai, $hasil1);
print json_encode($nilai, JSON_NUMERIC_CHECK);
$mysqli->close();
display my json from localhost/master/proyek/s-curve.php?balai=bl-1 :
Display Json Data
from my case above, can someone tell what error I can fix to be able to display the chart.
I am trying to add a dynamic select list to a Datatables Editor form. This is what I have tried:
var discipline_options = [];
$.getJSON('program_data/get_disciplines.php', function (data) {
$.each(data, function (index) {
discipline_options.push({
value: data[index].value,
label: data[index].text
});
});
editor.field( 'discipline_outcome.discipline_fk' ).update(discipline_options);
});
var editor = new $.fn.dataTable.Editor( {
ajax: "program_data/discipline_outcome_data.php",
table: "#discipline_outcome_table",
template: '#discipline_outcome_form',
fields: [ {
label: "Discipline:",
name: "discipline_outcome.discipline_fk",
type: "select",
placeholder: 'Choose discipline...',
placeholderDisabled: false,
placeholderValue: 0,
options: []
},...
The get_disciplines.php script is:
$data = array();
$query = "SELECT * FROM discipline";
$result = $connection->query( $query );
while ($row = mysqli_fetch_array($result)) {
$data[] = array("label"=>$row['discipline'], "value"=>$row['discipline_pk']);
}
$temp = array('disciplines[].discipline_pk'=>$data);
$json = array('options'=>$temp);
echo json_encode($json);
This script returns the following JSON, but the select list is still empty:
{
"options": {
"disciplines[].discipline_pk": [
{
"label": "Emergency Medicine",
"value": "1"
},
{
"label": "General Practice",
"value": "2"
},
{
"label": "Internal Medicine",
"value": "3"
}
]
}
}
I got it working using:
var discipline_options = [];
$.getJSON("program_data/get_disciplines.php", function(data) {
var option = {};
$.each(data, function(i,e) {
option.label = e.text;
option.value = e.id;
discipline_options.push(option);
option = {};
});
}
).done(function() {
editor.field('discipline.discipline_pk').update(discipline_options);
});
var editor = new $.fn.dataTable.Editor( {
ajax: "program_data/discipline_outcome_data.php",
table: "#discipline_outcome_table",
template: '#discipline_outcome_form',
fields: [ {
label: "Discipline:",
name: "discipline.discipline_pk",
type: "select",
placeholder: 'Choose discipline...',
placeholderDisabled: false,
placeholderValue: 0,
options: []
},...
and the get_disciplines.php:
$data = array();
$query = "SELECT * FROM discipline";
$result = $connection->query( $query );
while ($row = mysqli_fetch_array($result)) {
$data[] = array("text"=>$row['discipline'], "id"=>$row['discipline_pk']);
}
echo json_encode($data);
Hi guys i need help with Highcharts library, i have this array coming from php,
[{"name":"25% en cambio de aceite 76 lubricants","data":[["2015-09-07",1],["2015-09-23",2],["2015-09-24",3],["2015-09-30",3]]},{"name":"10% Descuento en filtro de aceite","data":[["2015-09-07",1],["2015-09-23",2],["2015-09-24",3],["2015-09-30",3],["2015-10-03",3],["2015-10-05",1],["2015-10-09",1],["2015-10-10",1]]}]
I need to show this as line chart dynamically, but have been unable to do it, i believe the error comes from the quotes in dates, needs to be in format [Date.UTC(2015, 2, 6), 3]
This is my php function that returns the json data
public function actionTransactionsRedeemed() {
// Transacciones Totales redimidas por merchant
$sql = "SELECT DISTINCT `transaction`.idPromotion, promotion.`name` FROM `transaction` INNER JOIN promotion ON `transaction`.idPromotion = promotion.idPromotion WHERE `transaction`.idMerchant = 2 AND `transaction`.idPromotion IS NOT NULL";
$idPromotion = Yii::app()->db->createCommand($sql)->queryAll();
$idPromotions = array();
$tempArray = array();
$result = array();
$i = 1;
$rs = array();
foreach($idPromotion as $i){
//process each item here
$id = $i["idPromotion"];
$tempArray['name'] = $i["name"];
$sql = "SELECT count(*) AS count, DATE(`transaction`.date) AS `date` FROM `transaction` WHERE `transaction`.idMerchant = 2 AND `transaction`.idPromotion = $id GROUP BY DATE(`transaction`.date)";
$transactionsRedeemed = Yii::app()->db->createCommand($sql)->queryAll();
foreach($transactionsRedeemed as $item2){
$rs[0] = $item2['date'];
$rs[1] = $item2['count'];
$tempArray['data'][] = $rs;
$rs = array();
}
$i++;
array_push($result, $tempArray);
}
//$result = json_encode($result, JSON_NUMERIC_CHECK);
//echo json_decode($result);
print json_encode($result, JSON_NUMERIC_CHECK);
}
And this is the Jquery that builds the chart
$(document).ready(function() {
var options = {
chart: {
type: 'spline',
renderTo: 'chart-merchant-day',
defaultSeriesType: 'spline',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Total de promociones redimidas',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%l%p', this.value);
}
}
},
yAxis: {
title: {
text: 'Transacciones'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%l%p', this.x-(24000*3600)) +'-'+ Highcharts.dateFormat('%l%p', this.x) +': <b>'+ this.y + '</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Count'
}],
credits: false
}
// Load data asynchronously using jQuery. On success, add the data
// to the options and initiate the chart.
jQuery.get('?r=/transactions/transactionsRedeemed', null, function(tsv) {
var lines = [];
traffic = [];
var data = $.parseJSON(tsv);
var x = 0;
//console.log(tsv);
$.each(data, function(i, item) {
//alert(item);
//console.log(item);
$.each(item, function(y, item2) {
if(y == "data"){
//console.log(item2);
try {
tsv = item2;
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
options.series[x].data.push([Date.parse(line[0]),line[1]]);
/*date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''), 10)
]);*/
});
} catch (e) { }
options.series[x].data = traffic;
} else if(y == "name"){
options.series[x].name = item2;
}
});
x++;
});
chart = new Highcharts.Chart(options);
//console.log(tsv.replace(/\"/g, ""));
//tsv = tsv.replace(/\"/g, "");
});
});
Any help will be greatly appreciated, im so exhausted at this point.
The function is actually simpler,
jQuery.get('?r=/transactions/transactionsRedeemed', null, function(tsv) {
var data = $.parseJSON(tsv);
$.each(data, function (i, item) {
options.series.push({
name: item['name'],
data: []
});
$.each(item['data'], function (j, dataitem) {
var dataitemvalue = null;
try {
dataitemvalue = [Date.parse(dataitem[0]), dataitem[1]];
} catch (e) {}
options.series[i].data.push(dataitemvalue);
});
});
chart = new Highcharts.Chart(options);
});
JSFiddle demo
I am using jTable with PHP Language,below is the jTable with data
code for jTable that i have tried...
<script type="text/javascript">
$(document).ready(function () {
$('#StudentTableContainer').jtable({
title: 'The Student List',
paging: true, //Enable paging
pageSize: 10, //Set page size (default: 10)
sorting: true, //Enable sorting
defaultSorting: 'Name ASC', //Set default sorting
actions: {
listAction: '/Demo/StudentList',
deleteAction: '/Demo/DeleteStudent',
updateAction: '/Demo/UpdateStudent',
createAction: '/Demo/CreateStudent'
},
fields: {
StudentId: {
key: true,
create: false,
edit: false,
list: false
},
Name: {
title: 'Name',
width: '23%'
},
EmailAddress: {
title: 'Email address',
list: false
},
Password: {
title: 'User Password',
type: 'password',
list: false
},
Gender: {
title: 'Gender',
width: '13%',
options: { 'M': 'Male', 'F': 'Female' }
},
CityId: {
title: 'City',
width: '12%',
options: '/Demo/GetCityOptions'
},
BirthDate: {
title: 'Birth date',
width: '15%',
type: 'date',
displayFormat: 'yy-mm-dd'
},
Education: {
title: 'Education',
list: false,
type: 'radiobutton',
options: { '1': 'Primary school',
'2': 'High school',
'3': 'University' }
},
About: {
title: 'About this person',
type: 'textarea',
list: false
},
IsActive: {
title: 'Status',
width: '12%',
type: 'checkbox',
values: { 'false': 'Passive', 'true': 'Active' },
defaultValue: 'true'
},
RecordDate: {
title: 'Record date',
width: '15%',
type: 'date',
displayFormat: 'dd.mm.yy',
create: false,
edit: false,
sorting: false //This column is not sortable!
}
}
});
//Load student list from server
$('#StudentTableContainer').jtable('load');
});
</script>
all thing with jTable working fine for me, but i want to add one more colomn named "Sr No" with number with 1,2,3.. etc before Name colomn.
Desired Output..
For jTable Reference :
EDIT:
code inside /Demo/StudentList method..
//Get record count
$result = mysql_query("SELECT COUNT(*) AS RecordCount FROM people;");
$row = mysql_fetch_array($result);
$recordCount = $row['RecordCount'];
//Get records from database
$result = mysql_query("SELECT * FROM people ORDER BY " . $_GET["jtSorting"] . " LIMIT " . $_GET["jtStartIndex"] . "," . $_GET["jtPageSize"] . ";");
//Add all records to an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['TotalRecordCount'] = $recordCount;
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
my best guess: put this before the 'name' field
srNo: {
title: 'Sr',
},
and fill the srNo in your json object inside /Demo/StudentList service.. you can use index in your loop
try this in your PHP codes:
//Add all records to an array
$rows = array();
$i = 1;
while($row = mysql_fetch_array($result))
{
$row['srNo'] = $i;
$rows[] = $row;
$i++;
}
crossing fingers!