How to get expandable details using datatable with tabletools? - php

How to get expandable details on click, I want my table details like:
In the above image when I click on (+) sign it will give me more fields of table, I want that type of functionality in my datatable.
Here is my html code :
<div class="row">
<div class="col-md-12">
<!-- BEGIN EXAMPLE TABLE PORTLET-->
<div class="portlet box blue-hoki">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-globe"></i>Prestart Hand Tools/Electric Power Tool Safety Checks
</div>
<div class="tools">
</div>
</div>
<div class="portlet-body">
<table class="table table-striped table-bordered table-hover" id="tblListing">
<thead>
<tr>
<th>Sr. No.</th>
<th>User</th>
<th>Model</th>
<th>Safety Inspection Due</th>
<th>MachineOwner</th>
<th>MachineType</th>
<th>FleetLicNum</th>
<th>YearOfMan</th>
<th>Manufactur</th>
<th>Image</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
var cOptions = [];
cOptions.columnDefs = [{
data: "srNo",
targets: 0,
orderable: false,
width: 50
}, {
data: "user_id",
targets: 1,
width: 150
}, {
data: "Model",
targets: 2,
width: 200
}, {
data: "SafetyInspectionDue",
targets: 3,
width: 150
}, {
data: "MachineOwner",
targets: 4,
width: 50
}, {
data: "MachineType",
targets: 5,
width: 50
}, {
data: "FleetLicNum",
targets: 6,
width: 50
}, {
data: "YearOfMan",
targets: 7,
width: 50
}, {
data: "Manufactur",
targets: 8,
width: 50
}, {
data: "ToolImage",
targets: 9,
orderable: false,
className: "dt-center",
width: 50
}, {
data: "action",
targets: 10,
orderable: false,
className: "dt-center",
width: 150
}];
cOptions.order = [
[1, 'asc']
];
cOptions.mColumns = [1, 2, 3, 4, 5, 6, 7, 8];
cOptions.url = 'ajax/mytoolbox.php';
Custom.initListingTable(cOptions);
</script>
My ajax/mytoolbox.php File :
<?php
include '../application/application_top.php';
include ROOT . '/application/function.php';
include_once '../../classes/mytoolbox.class.php';
$response['status'] = '';
$response['errorMsg'] = '';
$action = get_data('action', '');
if ($action == 'getList') {
$request = $_REQUEST;
$start = $request["start"];
$length = $request["length"];
$order = $request["order"];
$orderby = "Model DESC";
$search = $request["search"]["value"];
if ($order[0]['column'] == 1) {
$orderby = "reg.reg_fname " . strtoupper($order[0]['dir']);
} elseif ($order[0]['column'] == 2) {
$orderby = "Model " . strtoupper($order[0]['dir']);
} elseif ($order[0]['column'] == 3) {
$orderby = "SafetyInspectionDue " . strtoupper($order[0]['dir']);
} elseif ($order[0]['column'] == 4) {
$orderby = "MachineOwner " . strtoupper($order[0]['dir']);
} elseif ($order[0]['column'] == 5) {
$orderby = "MachineType " . strtoupper($order[0]['dir']);
} elseif ($order[0]['column'] == 6) {
$orderby = "FleetLicNum " . strtoupper($order[0]['dir']);
} elseif ($order[0]['column'] == 7) {
$orderby = "YearOfMan " . strtoupper($order[0]['dir']);
} elseif ($order[0]['column'] == 8) {
$orderby = "Manufactur " . strtoupper($order[0]['dir']);
}
$tableData = array();
$mytoolbox = new Mytoolbox();
$mytoolbox->cquery = "SELECT SQL_CALC_FOUND_ROWS mytoolbox.*,CONCAT(reg.reg_fname,' ',reg.reg_lname) as name from safe_my_tool_box as mytoolbox LEFT JOIN safe_register as reg on mytoolbox.user_id = reg.reg_id WHERE mytoolbox.is_delete='0'";
if ($search != "") {
$mytoolbox->cquery .= " AND (CONCAT(reg.reg_fname,' ',reg.reg_lname) LIKE '%" . $search . "%' OR Model LIKE '%" . $search . "%' OR YearOfMan LIKE '%" . $search . "%' )";
}
$mytoolbox->cquery .= " ORDER BY " . $orderby;
if ($length != -1)
$mytoolbox->cquery .= " LIMIT " . $start . "," . $length;
$mytoolbox->action = "get";
$mytoolbox_res = $mytoolbox->process();
foreach ($mytoolbox_res['res'] as $mytoolbox_row_key => $mytoolbox_row) {
$tableData[$mytoolbox_row_key]['srNo'] = '';
$tableData[$mytoolbox_row_key]['user_id'] = $mytoolbox_row['name'];
$tableData[$mytoolbox_row_key]['Model'] = $mytoolbox_row['Model'];
$tableData[$mytoolbox_row_key]['SafetyInspectionDue'] = $mytoolbox_row['SafetyInspectionDue'];
$tableData[$mytoolbox_row_key]['MachineOwner'] = $mytoolbox_row['MachineOwner'];
$tableData[$mytoolbox_row_key]['MachineType'] = $mytoolbox_row['MachineType'];
$tableData[$mytoolbox_row_key]['FleetLicNum'] = $mytoolbox_row['FleetLicNum'];
$tableData[$mytoolbox_row_key]['YearOfMan'] = $mytoolbox_row['YearOfMan'];
$tableData[$mytoolbox_row_key]['Manufactur'] = $mytoolbox_row['Manufactur'];
$tableData[$mytoolbox_row_key]['ToolImage'] = "<a href='#ImageModal' data-id='" . $mytoolbox_row['safe_my_tool_id'] . "' data-toggle='modal' alt='view'>Image</a>";
$tableData[$mytoolbox_row_key]['action'] = "<a href='#displayModal' data-id='" . $mytoolbox_row['safe_my_tool_id'] . "' data-toggle='modal' alt='view'>Question</a>"
. " | <a href='#confirmModal' data-id='" . $mytoolbox_row['safe_my_tool_id'] . "' data-toggle='modal' alt='Remove'>Delete</a>";
}
$data['data'] = $tableData;
$mytoolbox2 = new Mytoolbox();
$mytoolbox2->cquery = "SELECT FOUND_ROWS() as total_filter";
$mytoolbox2->action = "get";
$mytoolbox2_res = $mytoolbox2->process();
$mytoolbox1 = new Mytoolbox();
$mytoolbox1->cquery = "SELECT COUNT(*) AS total_tool_box FROM safe_my_tool_box WHERE is_delete='0'";
$mytoolbox1->action = "get";
$mytoolbox1_res = $mytoolbox1->process();
$data['recordsTotal'] = $mytoolbox1_res['res'][0]['total_tool_box'];
$data['recordsFiltered'] = $mytoolbox2_res['res'][0]['total_filter'];
echo json_encode($data);
exit(0);
}
?>
My custom.js file is :
var Custom = function () {
// private functions & variables
var myFunc = function(text) {
alert(text);
};
var initListingTable = function (cOptions) {
var table = $('#tblListing');
/* Table tools samples: https://www.datatables.net/release-datatables/extras/TableTools/ */
/* Set tabletools buttons and button container */
$.extend(true, $.fn.DataTable.TableTools.classes, {
container : "btn-group tabletools-dropdown-on-portlet",
buttons : {
normal : "btn btn-sm default",
disabled : "btn btn-sm default disabled"
},
collection: {
container : "DTTT_dropdown dropdown-menu tabletools-dropdown-menu"
}
});
var oTable = table.dataTable({
serverSide : true,
processing : true,
// Internationalisation. For more info refer to http://datatables.net/manual/i18n
language : {
aria : {
sortAscending : ": activate to sort column ascending",
sortDescending: ": activate to sort column descending"
},
emptyTable : "No data available",
info : "Showing _START_ to _END_ of _TOTAL_ entries",
infoEmpty : "No entries found",
infoFiltered : "(filtered from _MAX_ total entries)",
lengthMenu : "Show _MENU_ entries",
search : "Search:",
zeroRecords : "No matching records found"
},
// Or you can use remote translation file
//language: {
// url: '//cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Portuguese.json'
//},
searching : true,
order : cOptions.order,
lengthMenu : [
[25, 50, 100, -1],
[25, 50, 100, "All"] // change per page values here
],
// set the initial value
pageLength : 25,
dom : "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable
fnRowCallback: function(nRow, aData, iDisplayIndex){
var oSettings = oTable.fnSettings();
var index = oSettings._iDisplayStart + iDisplayIndex + 1;
$('td:eq(0)',nRow).html(index);
return nRow;
},
ajax : {
type : "POST",
url : cOptions.url,
data: ({
action : "getList"
}),
dataSrc: function ( json ) {
return json.data;
}
},
responsive: {
details: {
type: 'column'
}
},
columnDefs: cOptions.columnDefs,
// Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
// setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js).
// So when dropdowns used the scrollable div should be removed.
//dom: "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",
tableTools: {
sSwfPath : Metronic.getAssetsPath()+"global/plugins/datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf",
aButtons : [{
sExtends : "pdf",
sButtonText : "PDF",
mColumns : cOptions.mColumns
}, {
sExtends : "csv",
sButtonText : "CSV",
mColumns : cOptions.mColumns
}, {
sExtends : "xls",
sButtonText : "Excel",
mColumns : cOptions.mColumns
}, {
sExtends : "print",
sButtonText : "Print",
sInfo : 'Please press "CTR+P" to print or "ESC" to quit',
sMessage : "Generated by DataTables",
mColumns : cOptions.mColumns
}]
}
});
var tableWrapper = $('#tblListing_wrapper'); // datatable creates the table wrapper by adding with id {your_table_jd}_wrapper
tableWrapper.find('.dataTables_length select').select2({minimumResultsForSearch: Infinity}); // initialize select2 dropdown
};
var handleDatePickers = function () {
if ($().datepicker) {
$('.date-picker').datepicker({
rtl: Metronic.isRTL(),
autoclose: true
});
//$('body').removeClass("modal-open"); // fix bug when inline picker is used in modal
}
/* Workaround to restrict daterange past date select: http://stackoverflow.com/questions/11933173/how-to-restrict-the-selectable-date-ranges-in-bootstrap-datepicker */
};
var handleTimePickers = function () {
if (jQuery().timepicker) {
$('.timepicker-default').timepicker({
autoclose: true,
showSeconds: true,
minuteStep: 1
});
$('.timepicker-no-seconds').timepicker({
autoclose: true,
minuteStep: 5
});
$('.timepicker-24').timepicker({
autoclose: true,
minuteStep: 5,
showSeconds: false,
showMeridian: false
});
// handle input group button click
$('.timepicker').parent('.input-group').on('click', '.input-group-btn', function(e){
e.preventDefault();
$(this).parent('.input-group').find('.timepicker').timepicker('showWidget');
});
}
};
// public functions
return {
//main function
init: function () {
//initialize here something.
handleDatePickers();
handleTimePickers();
},
//some helper function
doSomeStuff: function () {
myFunc();
},
initListingTable: function(cOptions) {
initListingTable(cOptions);
},
handleDatePickers: function() {
handleDatePickers();
},
handleTimePickers: function() {
handleTimePickers();
}
};
}();
Datatable Listing view :
I want the fields Safety Inspection Due, MachineOwner, and MachineType in expandable details.

Related

Highchart not showing from JSON data

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.

How to extract the name of the DB and place it on an annual bar chart?

I was asked to make a graph where I should extract the names, along with the amount it has per year.
The way I did it was just to bring the total and the year for each portal name.
$portalInmobiliario = Ticket::selectRaw('year(created_at) as anio, count(id) as total')
->where('source_id', 1)
->groupBy('anio')
->get();
$tocToc = Ticket::selectRaw('year(created_at) as anio, count(id) as total')
->where('source_id', 2)
->groupBy('anio')
->get();
$enlaceInmobiliario = Ticket::selectRaw('year(created_at) as anio, count(id) as total')
->where('source_id', 3)
->groupBy('anio')
->get();
$webBI = Ticket::selectRaw('year(created_at) as anio, count(id) as total')
->where('source_id', 4)
->groupBy('anio')
->get();
$_portal = [];
foreach ($portalInmobiliario as $pi) {
$_portal[$pi->anio] = $pi->total;
}
$_toc = [];
foreach ($tocToc as $toct) {
$_toc[$toct->anio] = $toct->total;
}
$_enlace = [];
foreach ($enlaceInmobiliario as $inmobiliario) {
$_enlace[$inmobiliario->anio] = $inmobiliario->total;
}
$_web = [];
foreach ($webBI as $webbi) {
$_web[$webbi->anio] = $webbi->total;
}
$years = [];
$dataToc = [];
$dataPort = [];
$dataEnlace = [];
$dataWeb = [];
$currentYear = date('Y');
for ($i = $currentYear; $i > $currentYear - 5; $i--) {
$years[] = $i;
$dataPort[] = isset($_portal[$i]) ? $_portal[$i] : 0;
$dataToc[] = isset($_toc[$i]) ? $_toc[$i] : 0;
$dataEnlace[] = isset($_enlace[$i]) ? $_enlace[$i] : 0;
$dataWeb[] = isset($_web[$i]) ? $_web[$i] : 0;
}
My HTML y Script
<div class="row row-eq-height mt-2">
<div class="col-sm-12 col-lg-6">
<div class="iq-card">
<div class="iq-card-header d-flex justify-content-between">
<div class="iq-header-title">
<h4 class="card-title text-center">Graph</h4>
</div>
</div>
<div class="iq-card-body">
<div id="chartGeneral"></div>
</div>
</div>
</div>
</div>
<script>
const year = <?php echo json_encode($years)?>;
const portal = <?php echo json_encode($dataPort)?>;
const toctoc = <?php echo json_encode($dataToc)?>;
const enlace = <?php echo json_encode($dataEnlace)?>;
const bi = <?php echo json_encode($dataWeb)?>;
var optionsGeneral = {
series: [
{
name: 'Portal Inmobiliario',
data: portal
},
{
name: 'TOC TOC',
data: toctoc
},
{
name: 'Enlace Inmobiliario',
data: enlace
},
{
name: 'Web B-I',
data: bi
}
],
chart: {
type: 'bar',
height: 350,
stacked: true,
stackType: '100%'
},
plotOptions: {
bar: {
horizontal: true,
},
},
stroke: {
width: 1,
colors: ['#fff']
},
/*title: {
text: 'Fiction Books Sales'
},*/
xaxis: {
categories: year,
labels: {
formatter: function (val) {
return val
}
}
},
yaxis: {
title: {
text: undefined
},
},
tooltip: {
y: {
formatter: function (val) {
return val
}
}
},
fill: {
opacity: 1
},
legend: {
position: 'top',
horizontalAlign: 'left',
offsetX: 40
}
};
var chartGeneral = new ApexCharts(document.querySelector("#chartGeneral"), optionsGeneral);
chartGeneral.render();
</script>
Although this is how the code works, they asked me to extract the names from the DB, but I couldn't find a way to join the years and the total for each portal.

Kendo Grid inline editing with Kendo Upload return an null result

I had Kendo UI Grid with inline editing and one of my field (propertyLogo) I use kendoUpload to upload an image. With the kendoUpload function fileUploadEditor, I use saveUrl: "./image.php",and convert the image into base64 format to save into database. When I Add/Edit I manage to update all the field successfully except the propertyLogo field it return a NULL result. I do not know which part I'm doing wrong, but I'm not able to save the image into database. Here I'll provide my script.
My DataSource & Grid
/****************/
/** DATASOURCE **/
/****************/
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "./getPropertyMasterData.php",
type: "POST",
data: function() {
return {
method: "getPropertyMasterData",
}
}
},
update: {
url: "./getPropertyMasterData.php",
type: "POST",
data: function () {
console.log("I'm calling update!!");
return {
method: "editPropertyMasterData",
}
},
complete: function (e) {
$('#grid').data('kendoGrid').dataSource.read();
}
},
destroy: {
url: "./getPropertyMasterData.php",
type: "POST",
data: function () {
return {
method: "deletePropertyMasterData",
}
},
complete: function (e) {
$('#grid').data('kendoGrid').dataSource.read();
}
},
},
schema: {
model: {
id: "propertyID",
fields: {
propertyID: { editable: false, nullable: true }
active: { editable: false, nullable: false, defaultValue: 'y'},
propertyName: { editable: true,type: "string",validation: {required: {message: "Required"}} },
propertyLogo: { editable: true, type: "string",validation: {required: {message: "Required"}} },
propertyColor: { defaultValue: "#000", editable: true, validation: { required: {message: "Required"}} },
businessRegistrationNo: { editable: true,type: "string",validation: {required: {message: "Required"}} },
noOfRooms: { defaultValue: 1, editable: true,type: "number",validation: {min: 1, required: {message: "Required"}} }
}
}
},
pageSize: 25
}); // End of Kendo DataSource
/****************/
/** KENDO GRID **/
/****************/
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
sortable: true,
editable: { mode: "inline" },
columns: [
{ field: "active", title:" ", filterable: false,
template: "# if (active=='y'){# <span class='k-icon ehors-status-active-icon'></span> #} else {# <span class='k-icon ehors-status-inactive-icon'></span> # }#"},
{ field: "propertyName", title:"Property Name", width: "80" },
{ field: "businessRegistrationNo", title:"Business Reg. No.", width: "80" },
{ field: "propertyLogo", title:"Logo", width: "80", editor: fileUploadEditor
,template: "<div class='propertyLogo'><a></a>#=propertyLogo#</div>" },
{ field: "propertyColor", title:"Color", width: "80px", editor : getColor, template: function(dataItem) {
return "<div style='background-color: " + dataItem.propertyColor + ";'> </div>";
}},
{ field: "noOfRooms", title:"No of Rooms", width: "80px", format: "", template: "<div class='unit'>#= noOfRooms#</div>" },
//Button Name
{ command: [{ name: "edit", text: {
edit: "Edit",
update: "Update",
cancel: "Cancel"} }
], title: "" }
],
save: onSave, // <-- checking duplicate error.
noRecords: {template: "No Records" }
}).data("kendoGrid"); //end of kendo grid
function fileUploadEditor(container, options) {
$('<input type="file" id="fileUpload" name="fileUpload" /> ')
.appendTo(container)
.kendoUpload({
multiple:false,
async: {
saveUrl: "./image.php",
autoUpload: true,
},
validation: {
allowedExtensions: [".jpg", ".png", ".jpeg"]
},
success: onSuccess, // just a console log to view progress
upload: onUpload, // just a console log to view progress
progress: onProgress // just a console log to view progress
});
}
My image.php
Image will convert into base64 and store into hexString variable. Once getPropertyMasterData.php been called it will fetch hexString value. Currently in here I can see it successful return a value.
<?php
$file = $_FILES['fileUpload'];
$fileName = $_FILES['fileUpload']['name'];
$fileTmpName = $_FILES['fileUpload']['tmp_name']; //directory location
$fileSize = $_FILES['fileUpload']['size'];
$fileError = $_FILES['fileUpload']['error']; //default 0 | 1 got error
$fileExt = explode('.', $fileName); //split file name to get ext name.
$fileActualExt = strtolower(end($fileExt)); //change to lowercase for the extension file
$allowed = array('jpg','jpeg','png');
if (!in_array($fileActualExt, $allowed)) {
return ['error' => 'You cannot upload files of this type!'];
}
if ($fileError !== 0) {
return ['error' => 'Error occur when upload file!'];
}
if ($fileSize > 500000) {
return ['error' => 'Your file size is too big!'];
}
$fileDestination = './uploads/' . $fileName;
move_uploaded_file($fileTmpName, $fileDestination);
$data = file_get_contents($fileTmpName);
return ['hexString' => base64_encode($data)];
?>
My getPropertyMasterData.php
Supposedly $uploadPayload['hexString'] will fetch a variable from image.php but somehow it return NULL result. Other fields works fine.
<?php
$propertyID = "1";
include($_SERVER['DOCUMENT_ROOT'] . '/TM.pdo.php');
$ehorsObj = new TM();
$ehorsObj->TM_CONNECT($propertyID);
$uploadPayload = require "image.php"; // READ FILE FROM image.php | Return NULL result
if (isset($uploadPayload['error'])) {
// echo $uploadPayload['error']);
/* do something in case of error */
}
$method = $_POST['method'];
switch ($method){
case "getPropertyMasterData" :
$method($ehorsObj);
break;
case "editPropertyMasterData" :
$method($ehorsObj, $uploadPayload['hexString']);
break;
default:
break;
}
/** READ **/
function getPropertyMasterData($ehorsObj) {
$getcheckbox = (isset($_POST['c1']) ? $_POST['c1'] : "all"); // by default select *
$sql = "SELECT * FROM tblAdmProperty ";
if ($getcheckbox == "true") {
$sql .= " WHERE active = 'y' ";
}
$sql .= " ORDER BY 2 ASC " ;
$array = array();
$GetResult = $ehorsObj->FetchData($sql, $ehorsObj->DEFAULT_PDO_CONNECTIONS);
while ($row = $GetResult->fetch()){
$array[] = $row;
}
header("Content-type: application/json");
$result = json_encode($array);
echo $result;
}
/** EDIT **/
function editPropertyMasterData($ehorsObj, $NewHexString) {
$propertyID = (isset($_POST['propertyID']) ? $_POST['propertyID'] : '');
$propertyName = (isset($_POST['propertyName']) ? $_POST['propertyName'] : '');
$propertyLogo = (isset($_POST['propertyLogo']) ? $_POST['propertyLogo'] : '');
$propertyColor = (isset($_POST['propertyColor']) ? $_POST['propertyColor'] : '');
$businessRegistrationNo = (isset($_POST['businessRegistrationNo']) ? $_POST['businessRegistrationNo'] : '');
$noOfRooms = (isset($_POST['noOfRooms']) ? $_POST['noOfRooms'] : '');
$active = (isset($_POST['active']) ? $_POST['active'] : '');
$sqlUpdate = " UPDATE tblAdmProperty
SET propertyName = '" . $propertyName . "',
propertyLogo = '" . $NewHexString . "',
propertyColor = '" . $propertyColor . "',
businessRegistrationNo = '" . $businessRegistrationNo . "',
noOfRooms = '" . $noOfRooms . "',
active = '" . $active . "'
WHERE propertyID = '" . $propertyID . "' ";
$ehorsObj->ExecuteData($sqlUpdate, $ehorsObj->DEFAULT_PDO_CONNECTIONS);
}
?>
It works if I use cookies or session but I try to avoid using that. I hope I provide a clear explanation.
Finally, I manage to get it works.
First, I create a hidden textbox <input type="hidden" id='uploadedFile' data-bind="value: propertyLogo" />
Fixed my fileUploadEditor function and add remove.php (optional). onSucces event will fetch the server response in image.php and push into textbox value which I create before.
function onSuccess(e) {
console.log(e.response);
/* push server respoonse to texbox */
$("#uploadedFile").val(e.response);
}
function fileUploadEditor(container, options){
$('<input type="file" id="propertyLogo" name="propertyLogo" /> ')
.appendTo(container)
.kendoUpload({
multiple:false,
async: {
saveUrl: "image.php",
removeUrl: "remove.php",
autoUpload: true,
},
validation: {
allowedExtensions: [".jpg", ".png", ".jpeg"]
},
success: onSuccess
});
$("<span class='k-invalid-msg' data-for='propertyLogo'></span>").appendTo(container);
}
image.php after convert into base64, it need to be in json format
<?php
$fileParam = "propertyLogo";
$uploadRoot = "uploads/";
$files = $_FILES[$fileParam];
if (isset($files['name'])){
$error = $files['error'];
if ($error == UPLOAD_ERR_OK) {
$fileSize = $files['size'];
if ($fileSize < 500000) { //500000 = 500mb
$targetPath = $uploadRoot . basename($files["name"]);
$uploadedFile = $files["tmp_name"];
/* get a full paths */
$fullpath = getcwd();
$newTargetPath = $fullpath . '/' . $targetPath;
move_uploaded_file($uploadedFile, $newTargetPath);
/* convert data into base64 */
$data = file_get_contents($uploadedFile);
$hex_string = base64_encode($data);
header('Content-Type: application/json');
echo json_encode($hex_string);
} else {
echo "Your file size is too big! ";
}
} else {
echo "Error code " . $error;
}
}
// Return an empty string to signify success
echo "";
?>
remove.php
<?php
$fileParam = "propertyLogo";
$uploadRoot = "uploads/";
$targetPath = $uploadRoot . basename($_POST["name"]);
unlink($targetPath);
echo "";
?>
Lastly on my Kendo ui Grid save event i add this line, basically fetch the value from textbox and set into my propertyLogo field
save: function(e){ e.model.set("propertyLogo",$("#uploadedFile").val()); }

How to give different row id's for two different variables in the same table, one for folders and the other for medias?

I need some help plz!!
I need to give each variable an id to use it later to make an ajax click on method action to enter the $folder subdirectory's inside the table.
Do I have to do that in the controller or in the ajax?
The data tables plugin is used in the application: https://datatables.net/
// These are the three functions: Controller function, Ajax function, and Bootstrap, as you can see the folders at the top of the table then the medias will be listed, I am not having any problem with the code and its working fine.
public function ajaxSearchMedias() {
$this->checkAccessPlaylists(false) ;
$this->loadModelSpe('Media');
$this->loadModelSpe('media');
$orderby = 'name' ;
$orderway = 'ASC' ;
$search = NULL ;
if(isset($_POST['order'][0]["column"])) {
$column_to_order = (int) $_POST['order'][0]["column"] ;
if($column_to_order == 2)
$orderby = 'length' ;
}
if(isset($_POST['order'][0]["dir"])) {
$way_to_order = $_POST['order'][0]["dir"] ;
if(strtolower($way_to_order) == 'desc')
$orderway = 'DESC' ;
}
if($_POST['search']["value"])
$search = $_POST['search']["value"] ;
$data = array();
// Display folders in the content playlists
if(isset($_POST['folderId']) && $_POST['folderId'] != -1) {
$level = $this->media->getFolderLevel($_POST['folderId'])->level;
$level++;
$parentFolder = $_POST['folderId'];
$folders = $this->media->getFoldersByParentFolderId($_POST['folderId']);
$medias = $this->media->getMediasByParentFolderId($_POST['folderId']);
}else {
$siteId = $_SESSION["sess_id_site"];
$folders = $this->media->getRootFoldersBySiteId($siteId);
$medias = $this->media->getRootMediasBySiteId($siteId);
}
if($folders) {
foreach ($folders as $folder){
//$name = $newtext = wordwrap( $one_media->name, 15, "\n", true );
$name = $folder->name;
$name = '<span>'.$name.'</span>';
$unformatted_length = Helper::getLengthForMedia(array("type" => $folder->type)) ;
$length = Helper::convertSecondsToMinutesSeconds($unformatted_length) ;
$orientation_and_type_icon = '<div class="" data-name="'.htmlspecialchars($folder->name, ENT_QUOTES, 'UTF-8').'" data-length="'.$length.'" data-unformatted_length="'.$unformatted_length.'" data-id="'.$one_media->id.'" data-type="media" >' ;
$orientation_and_type_icon .= '<span class="icon">'.Helper::getIconForTypeAndOrientationForMedia($folder).'</span>' ;
$orientation_and_type_icon .= '<span class="thumbnail" style="display:none;">'.Helper::getThumbnailForMedia($folder, $this->current_id_company, $this->current_id_site, "img-thumbnail").'</span>' ;
$orientation_and_type_icon .= '<button type="button" id="'.$folder->name.'" > <span class="glyphicon glyphicon-plus-sign"></span></span></button>' ;
$orientation_and_type_icon .= '</div>' ;
array_push($data, array('orientation_and_type_icon' => $orientation_and_type_icon, 'name' => $name, 'length' => $length));
}
}
// Display Medias in the content playlist
$medias = $this->Media->getMediasForContentPlaylists($search, $orderby, $orderway, 500, $this->current_id_site, $id_folder = NULL);
if($medias) {
foreach ($medias as $one_media){
//$name = $newtext = wordwrap( $one_media->name, 15, "\n", true );
$name = $newtext = $one_media->name;
$name = '<span>'.$name.'</span>';
$unformatted_length = Helper::getLengthForMedia(array("type" => $one_media->type, "length" => $one_media->length)) ;
$length = Helper::convertSecondsToMinutesSeconds($unformatted_length) ;
$orientation_and_type_icon = '<div class="pl_media_data" data-name="'.htmlspecialchars($one_media->name, ENT_QUOTES, 'UTF-8').'" data-length="'.$length.'" data-unformatted_length="'.$unformatted_length.'" data-id="'.$one_media->id.'" data-type="media" >' ;
$orientation_and_type_icon .= '<span class="icon">'.Helper::getIconForTypeAndOrientationForMedia($one_media).'</span>' ;
$orientation_and_type_icon .= '<span class="thumbnail" style="display:none;">'.Helper::getThumbnailForMedia($one_media, $this->current_id_company, $this->current_id_site, "img-thumbnail").'</span>' ;
$orientation_and_type_icon .= '</div>' ;
array_push($data, array('orientation_and_type_icon' => $orientation_and_type_icon, 'name' => $name, 'length' => $length));
}
}
$json_result = json_encode(array("data" => $data));
print $json_result;
}
// This is the ajax function, this function list media's and folders using data tables plugin without any problem, the main problem is giving an id to folders different than the media's so I can use it to make the click on for the folders.
this.getMediaList = function() {
var jqxhr = $.getJSON( url + 'plugins/DataTables-1.10.12/media/js/i18n/fr_FR.json', function( data ) {});
jqxhr.done(function(data) {
self.pl_dt_language_json = data ;
var languages_dt = self.pl_dt_language_json ;
languages_dt = $.extend(languages_dt, {"sSearch": ""});
self.pl_medias_dt = $('#pl_medias').DataTable({
language: languages_dt,
"columns": [
{ "data": "type" },
{ "data": "orientation_and_type_icon" },
{ "data": "name" },
{ "data": "length" },
],
"columnDefs": [
{ "searchable": false, "orderable": false, "targets": 0 },
{ className: "pl_media_cell_type", "targets": [ 0 ] } ;
{ className: "pl_media_cell_icon", "targets": [ 1 ] } ,
{ className: "pl_media_cell_name", "targets": [ 2 ] } ,
{ className: "pl_media_cell_length", "targets": [ 3 ] }
],
"order": [[ 1, 'asc' ]],
initComplete: function(settings, json) {
// search
if($('#pl_medias_filter input').eq(0).size() > 0) {
$('#pl_medias_filter input').eq(0).attr("placeholder", "Rechercher un fichier") ;
$('#pl_medias_filter input').unbind();
$('#pl_medias_filter input').on( 'keyup', function () {
var searchInput = $(this).val();
if(searchInput.length == 0) {
window.clearTimeout(self.pl_medias_dt_filter_status);
self.pl_medias_dt.search( searchInput ).draw();
} else {
if(searchInput.length < 3) {
window.clearTimeout(self.pl_medias_dt_filter_status);
self.pl_medias_dt_filter_status = setTimeout(function() {
self.pl_medias_dt.search( searchInput ).draw() ;
}, 3000);
} else {
window.clearTimeout(self.pl_medias_dt_filter_status);
self.pl_medias_dt_filter_status = setTimeout(function() {
self.pl_medias_dt.search( searchInput ).draw()
}, 1000);
}
}
});
}
},
drawCallback: function(settings) {
// refresh drag and drop
self.initDragDropSortElementForContentPlaylist();
},
"serverSide": true,
"paging": false,
"lengthChange" : false,
"scrollY": 122,
"info": false,
"ajax": {
url : url + "playlists/ajaxSearchMedias", // json datasource
type: "post"
},
"dom": '<lf<t>ip>'
});
});
},
// This is the Bootstrap script
<div class="pl_block_wrapper pl_block_media_wrapper row">
<div class="col-xs-2 pl_block_label"><span>AUTOPROMO</span></div>
<div class="col-xs-10 pl_block_container_middle">
<table id="pl_medias" class="table table-striped table-bordered" width="100%" cellspacing="0">
<thead>
<tr>
<th>Type</th>
<th>Nom</th>
<th>Durée</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
As you can see the three Bootstrap ajax jquery and PHP scripts.
I found a simple solution to add an id and a class :-) :
$('#pl_medias tr').attr('id', 'table-row-id');
$('#pl_medias tr').attr('class', 'table-row-class');
Thank you very much!

Highcharts: Force show xAxis with datetime

My highcharts chart is showing like this now:
http://img90.imageshack.us/img90/3892/chart1p.png
But I need it to look like this:
http://img545.imageshack.us/img545/1333/chart2p.png
Currently its not showing empty values by hours.
My code:
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function () {
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'spline'
},
title: {
text: 'Earnings Today',
},
subtitle: {
text: ''
},
xAxis: {
type: 'datetime',
tickInterval: 3600 * 1000,
tickWidth: 0,
labels: {
align: 'center',
formatter: function () {
return Highcharts.dateFormat('%l%p', this.value);
}
},
},
yAxis: {
title: {
text: 'Earnings'
},
min: 0,
tickInterval: 2,
},
plotOptions: {
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 1
}
}
},
tooltip: {
valueDecimals: 2,
crosshairs: true,
formatter: function () {
return '$' + this.y;
}
},
series: [{
name: 'Earnings Today, USD'
}
]
}
jQuery.get('data_today.php', null, function (tsv) {
var lines = [];
earnings = [];
try {
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function (i, line) {
line = line.split(/\t/);
date = Date.parse(line[0] + ' UTC');
val = line[1];
earnings.push([date, parseFloat(line[1].replace(',', '.'), 10)]);
});
} catch (e) {}
options.series[0].data = earnings;
chart = new Highcharts.Chart(options);
});
});
</script>
data_today.php
<?php
session_start();
require_once('config.php');
require_once('config_mysql.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if (!$db)
{
die("Unable to select database");
}
$result = mysql_query("SELECT earn_date,SUM(amount) as val FROM user_earnings WHERE user_id='$USER_ID' AND DATE(earn_date) = DATE(NOW()) GROUP BY earn_date");
if ($result)
{
while ($row = mysql_fetch_array($result))
{
$d = date("l, F, j, Y G:i:s", strtotime($row["earn_date"]));
echo $d . "\t" . $row['val'] . "\n";
}
}
else
{
die(mysql_error());
}
mysql_close($link);
?>
So, (if its not enough clear yet) I need this code to show whole day and show also empty values by hour.
I have almost zero experience of highcharts and javascript, so I need some help with this :)
Also looking for alternative way for running MySql query inside index.php so I dont need data_today.php
Thanks
Set the xAxis as below
xAxis: {
ordinal: false
}
For empty spaces you should have null values. Then set connectNulls: false.
Example

Categories