I'm trying to use the date and time input in datatables used here https://editor.datatables.net/examples/dates/datetime.html
This is what I've tried
<script type="text/javascript" src="<?php echo base_url('assets/js/jquery-3.1.1.min.js');?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/js/materialize.min.js');?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/js/jquery.dataTables.js');?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/js/moment.js');?>"></script>
<script type="text/javascript">
//use a global for the submit and return data rendering in the examples
var editor;
$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
table: '#receivablesLogs',
fields: [ {
label: 'Date:',
name: 'date'
type: 'datetime',
def: function () { return new Date(); },
format: 'MM-DD-YYYY',
fieldInfo: 'US style m-d-y date input'
},
{
label: 'Invoice Number:',
name: 'invoice_number'
},
{
label: 'Customer Name:',
name:'customer_name'
},
{
label: 'Total Amount:',
name: 'total_amount'
},
{
label: 'Due Date:',
name: 'due_date'
type: 'datetime',
def: function () { return new Date(); },
format: 'MM-DD-YYYY',
fieldInfo: 'US style m-d-y date input'
}
]
} );
$('#receivablesLogs').DataTable( {
dom: 'Bfrtip',
columns: [
{data: 'date'},
{data: 'invoice_number'},
{data: 'customer_name'},
{data: 'total_amount'},
{data: 'due_date'}
],
select: true,
order: [[ 0, 'asc' ]],
bFilter: false,
bLengthChange: false,
paging: false,
bFiler: false
});
});
</script>
and here is my table
<table id="receivables" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Date</th>
<th>Invoice Number</th>
<th>Customer Name</th>
<th>Total Amount</th>
<th>Due Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>03/31/2014</td>
<td>12456</td>
<td>Customer One</td>
<td>160,000.00</td>
<td>04/25/2015</td>
</tr>
<tr>
<td>02/28/2015</td>
<td>12456</td>
<td>Customer One</td>
<td>160,000.00</td>
<td>04/25/2015</td>
</tr>
</tbody>
</table>
But I don't know where I went wrong. I imported the correct js files but it doesn't display correctly. This is the output that I'm getting
Also I don't get what this line ajax: '../php/datetime.php' is for. I don't see what is the datetime.php that the documentation is referring to.
This is my first time trying datatables so I don't know where I did wrong. I already tried the basic creation of datatables and it worked but I had a problem when I tried to incorporate the date and time input in my codes.
UPDATE 1: There exists a server side script like this in the documentation
<?php
/*
* Example PHP implementation used for date time examples
*/
// DataTables PHP library
include( "../../php/DataTables.php" );
// Alias Editor classes so they are easy to use
use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Mjoin,
DataTables\Editor\Options,
DataTables\Editor\Upload,
DataTables\Editor\Validate;
// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'users' )
->fields(
Field::inst( 'first_name' ),
Field::inst( 'last_name' ),
Field::inst( 'updated_date' )
->validator( 'Validate::dateFormat', array(
'empty' => false,
'format' => 'm-d-Y g:i A'
) )
->getFormatter( 'Format::datetime', array(
'from' => 'Y-m-d H:i:s',
'to' => 'm-d-Y g:i A'
) )
->setFormatter( 'Format::datetime', array(
'from' => 'm-d-Y g:i A',
'to' => 'Y-m-d H:i:s'
) ),
Field::inst( 'registered_date' )
->validator( 'Validate::dateFormat', array(
'format' => 'j M Y H:i'
) )
->getFormatter( 'Format::datetime', array(
'from' => 'Y-m-d H:i:s',
'to' => 'j M Y H:i'
) )
->setFormatter( 'Format::datetime', array(
'from' => 'j M Y H:i',
'to' => 'Y-m-d H:i:s'
) )
)
->process( $_POST )
->json();
Where should I put this?
I pull this code snippet from the site you provided a link for:
$('#example').DataTable( {
dom: 'Bfrtip',
ajax: '../php/datetime.php',
columns: [
{ data: 'first_name' },
{ data: 'last_name' },
{ data: 'updated_date' },
{ data: 'registered_date' }
],
select: true,
buttons: [
{ extend: 'create', editor: editor },
{ extend: 'edit', editor: editor },
{ extend: 'remove', editor: editor }
]
} );
Ajax is a set of techniques to load data dynamically, behind the scenes.
Some information here: https://developer.mozilla.org/en-US/docs/AJAX
The link: "../php/datetime.php" is given as an example.
datetime.php is a file you would have to actually make in php.
In this case, datetime.php runs on the back-end, and probably queries some database.
Related
I want to set up a datatable on my website and I found a table I want to use here and I have been trying to convert it over to what I need. I have not had much success in this endeavor. My current situation is the table is not populating with rows from a database table and I am getting a json response error. I can open the inspector look at the php file that queries the database returns json data and I can see that I am returning data in the format
{"data":[
{"ssn":"100192686","dob":"1977-02-01","fn":"Latoyia","mi":"H","ln":"Herdon"},
{"ssn":"100263201","dob":"1962-06-15","fn":"Adena","mi":"M","ln":"Couch"}
]}
which according to a json validator is valid json but when I reload my page I get an error
"table id=example - Invalid JSON response".
So if the json data is in the correct format but is not being returned correctly what do I do? here is a gihub for the project. I have included the mysql database file I am working with as well as a text file that has XHR results in it. I feel like this line $('#example').DataTable( { javascript is where my issue is
<?php
include_once 'header.php';
?>
<script src = 'https://code.jquery.com/jquery-1.12.4.js'></script>
<script src = 'https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js'></script>
<script src = 'https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js'></script>
<script src = 'https://cdn.datatables.net/select/1.2.5/js/dataTables.select.min.js'></script>
<script src = 'JS/dataTables.editor.min.js'></script>
<link rel = "stylesheet" href = "https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<link rel = "stylesheet" href = "https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css">
<link rel = "stylesheet" href = "https://cdn.datatables.net/select/1.2.5/css/select.dataTables.min.css">
<link rel = "stylesheet" href = "https://editor.datatables.net/extensions/Editor/css/editor.dataTables.min.css">
<section class="main-container">
<div class="main-wrapper">
<h2>Home</h2>
<?php
if (isset($_SESSION['u_id'])) {
$sql = "SELECT * FROM employee;";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0){
echo
"<table id='example' class='display' cellspacing='0' width='100%'>
<thead>
<tr>
<th></th>
<th>ssn</th>
<th>dob</th>
<th>first</th>
<th>MI</th>
<th>last</th>
</tr>
</thead>";
}
}
?>
</div>
</section>
<script>
console.log("In the script open");
var editor; // use a global for the submit and return data rendering in the examples
$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
ajax: "infograb.php",
table: "#example",
fields: [ {
label: "Social#:",
name: "ssn"},
{
label: "DOB:",
name: "dob"},
{label: "First Name:",
name: "fn"},
{
label: "Middle Initial:",
name: "mi"},
{
label: "Last Name:",
name: "ln"
}
]
} );
$('#example').on( 'click', 'tbody td', function (e) {
var index = $(this).index();
if ( index === 1 ) {
editor.bubble( this, ['fn', 'mi', 'ln'], {
title: 'Edit name:'
} );
}
else if ( index === 2 ) {
editor.bubble( this, {
buttons: false
} );
}
else if ( index === 3 ) {
editor.bubble( this );
}
} );
var testData = [{
"ssn": "98727748",
"dob": "2016-02-05",
"fn": "jake",
"mi": "a",
"ln": "butler"
}];
$('#example').DataTable( {
dom: "Bfrtip",
ajax:{
url: 'infograb.php',
type: 'POST',
data: {
json: JSON.stringify({ "data": testData })
},
dataSrc: 'data'
},
columns: [
{//sets the checkbox
data: null,
defaultContent: '',
className: 'select-checkbox',
orderable: false
},
{ data: "dob" },
{ data: "ssn" },
{ data: "fn" },
{ data: "mi" },
{ data: "ln" },
],
order: [ 1, 'asc' ],
select: {
style: 'os',
selector: 'td:first-child'
},
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
]
} );
} );
console.log("End script");
</script>
<?php
include_once 'footer.php';
?>
and here is the php file that queries the database and returns(allegedly) the json data
<?php
include_once 'dbconn.php';
$rows = array();
$sql = "SELECT * FROM employee";
$result = $conn->query($sql) or die("cannot write");
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
echo "<pre>";
print json_encode(array('data'=>$rows));
echo "</pre>";
?>
I have been at this for about 24 hours now, and I feel like I have a bonehead mistake here I just can't figure it out. Any help would talk me down off the cliff at this point.
Datatables can be a pain and it's worthwhile to make sure you read the documents provided by them as much as you can.
I can see 2 issues running over your code without running tests. First one is infograb.php won't save any data sent to it because all it does is return data when it's loaded. Secondly you are using the initiation code of the datatable to try and send data (presumably for the inline editing as you don't seem to require any variables to be sent for the data requested). My first step would be taking it back a step:
ajax:{
url: 'infograb.php',
type: 'POST',
data: {
json: JSON.stringify({ "data": testData })
},
dataSrc: 'data'
},
Should go back to
ajax:{
url: 'infograb.php',
},
Remove the pre tags from infograb.php as well as they are unnecessary.
That should load the data into the table for you. You can then start working on the editing side.
Worthwhile Reading and Documentation:
Ajax sourced data
PHP libraries
DataTables Editor 1.7.3 - PHP 5.3+ libraries
I'm using datatable plugin and want to refresh table by ajax. I've read here to make my ajax return shows in table but it doesn't work. Here is my html code:
<button type="button" onclick="rld()">test</button>
<table id="sample_1">
<thead>
<tr>
<th> 1 </th>
<th> 2 </th>
<th> 3 </th>
</tr>
</thead>
</table>
My java function:
function rld(){
var table = $('#sample_1').DataTable( {
ajax: '<?php echo site_url('admin/test'); ?>',
deferRender: true,
columns: [
{ data: '1' },
{ data: '2' },
{ data: '3' }
],
rowId: 'extn',
select: true,
dom: 'Bfrtip',
buttons: [
{
text: 'Reload table',
action: function () {
table.ajax.reload();
}
}
]
} );
}
I can't get what the problem is. there in no alerts but in the console i get TypeError: f is undefined
and TypeError: c is undefined
Which i don't know why cause my json return is correct (checked in [JSONLint][3]).
Thanks in advance.
Thank you all for your attention :)
Found that i didn't call where the data goes when returned as json and the json field's name isn't equal to the column data field name. So make this adjustment:
function reload_table(){
var table = $('#sample_1').DataTable();
table.destroy();
var table = $('#sample_1').DataTable( {
"processing": true,
"dataType": 'json',
ajax: '<?php echo site_url('admin/relaod_table'); ?>',
deferRender: true,
columns: [
{ data: 'user_firstname' },
{ data: 'user_lastname' },
{ data: 'user_status' },
{ data: 'user_created_date' },
],
dom: 'Bfrtip',
buttons: [
{
text: 'Reload table',
action: function () {
table.ajax.reload();
}
}
]
} );
}
I have a table with tones of records and I need some links inside the table, so the problem is about formatting...
The first row is a link of the name of the patient to his single page and the last row is a collection of links for edit and delete the patient.
The problem:
Now with this code in the first row don't appear the name (row[1]),
appear the surnames (row[2]) but the link is ok (row[0])
In the last row both links are working good, but thickybox is not
working, the link is opened in a new page.
Can somebody help me with that? thank's in advance!!! :)
Server-side processing script:
$columns = array(
array(
'db' => 'id',
'dt' => 0,
'formatter' => function( $d, $row ) {
$links=''.$row[1].'';
return $links;
}),
array( 'db' => 'apellidos', 'dt' => 1 ),
array( 'db' => 'tel_mov', 'dt' => 2 ),
array( 'db' => 'terapeuta', 'dt' => 3 ),
array(
'db' => 'id',
'dt' => 4,
'formatter' => function( $d, $row ) {
$links2='<img src="ima/edit.png" /> | <img src="ima/close.png" />';
return $links2;
}),
);
Javascript:
$(document).ready(function() {
$('#tablet').DataTable({
"language": {
"url": "https://cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json"},
"scrollY": "400px",
"scrollCollapse": true,
"processing": true,
"serverSide": true,
"ajax": "load.php"
});
} );
I got it ;)
For the links names problems:
Just add first column of the table a id data and if you don't need it hide it with options in the javascript ("bVisible": false)
So now the $row[0] is always the id and the $row[1] the name...
For the thickbox problem:
Just add "aoColumns" whith the options an after "fnDrawCallback"
"aoColumns": [
{ "sTitle": "id","bVisible": false},
{ "sTitle": "Nombre" },
{ "sTitle": "Apellidos" },
{ "sTitle": "Móbil","bSortable": false },
{ "sTitle": "Fijo","bSortable": false },
{ "sTitle": "Terapeuta","bSortable": false },
{ "sTitle": "Edición","bSortable": false,"bSearchable": false }],
"fnDrawCallback": function() {
tb_init('a.thickbox');
}
I don't know if is the best way but is working for me ;)
I'm using codeigniter and datatables for my view data. But i'm stuck how to get sum column. I have 2 fields named barang_qty, and barang_qty_toko. I need to sum this and display on datatables.
This is my Controller :
function ajax_tableBarang(){
if(!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}else{
$this->load->library('datatables_ssp');
$table = 'barang';
$primaryKey = 'barang_id';
$columns = array(
array( 'db' => 'barang_id', 'dt' => 'DT_RowID' ),
array( 'db' => 'barang_kode', 'dt' => 'barang_kode' ),
array( 'db' => 'barang_type', 'dt' => 'barang_type' ),
array( 'db' => 'barang_size', 'dt' => 'barang_size' ),
array( 'db' => 'barang_qty', 'dt' => 'barang_qty'), //I want this field result from summation of barang_qty and barang_qty_toko
array( 'db' => 'barang_harga', 'dt' => 'barang_harga' ),
array( 'db' => 'barang_klasifikasi', 'dt' => 'barang_klasifikasi'),
);
$sql_details = array(
'user' => 'user',
'pass' => 'passwd',
'db' => 'pjtomato',
'host' => 'localhost'
);
$where = "";
echo json_encode(Datatables_ssp::simple($_GET, $sql_details, $table, $primaryKey, $columns, $where));
}
}
And this is my view :
<div role="tabpanel" class="tab-pane fade in active" id="tab-all">
<table id="tableAllItem" class="table table-bordered table-striped table-hover" cellspacing="0" width="100%">
<thead>
<tr class="info">
<th>#</th>
<th>Kode</th>
<th>Jenis</th>
<th>Ukuran</th>
<th>Quantity</th> // Total of quantity (summation of barang_qty + barang_qty_toko) will display here
<th>Harga</th>
<th>Klasifikasi</th>
</tr>
</thead>
</table>
And this is the javascript for datatables:
<script type="text/javascript">
$.fn.dataTableExt.oApi.fnPagingInfo = function (oSettings){
return{
"iStart": oSettings._iDisplayStart,
"iEnd": oSettings.fnDisplayEnd(),
"iLength": oSettings._iDisplayLength,
"iTotal": oSettings.fnRecordsTotal(),
"iFilteredTotal": oSettings.fnRecordsDisplay(),
"iPage": Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength),
"iTotalPages": Math.ceil(oSettings.fnRecordsDisplay() / oSettings._iDisplayLength)
};
};
var t = $('#tableAllItem').DataTable({
"processing": true,
"serverSide": true,
"ajax": "<?php echo site_url('cAdminPage/ajax_tableBarang'); ?>",
"columns": [
{ "data": "barang_kode" },
{ "data": "barang_kode" },
{ "data": "barang_type" },
{ "data": "barang_size" },
{ "data": "barang_qty"},
{ "data": "barang_harga" },
{ "data": "barang_klasifikasi" },
],
"order": [[1, 'asc']],
"rowCallback": function (row, data, iDisplayIndex){
var info = this.fnPagingInfo();
var page = info.iPage;
var length = info.iLength;
var index = page * length + (iDisplayIndex + 1);
$('td:eq(0)', row).html(index);
}
});
Please advice,
Thanks
I am putting together a simple join query using Datatables Editor however am getting errors which I don't understand. My code is below:
HTML
<!-- Actions -->
<div id="divActions" class="tab-pane fade">
<ul class="nav nav-list">
<!-- Actions Tab Header -->
<legend id="lgdActions">Actions</legend>
<table id="tblActions" class="display" cellspacing="0" width="100%"></table>
</ul>
</div>
Javascript
Actions Datagrid
$('#tblActions').DataTable({
dom: "Tfrtip",
lengthChange: false,
bAutoWidth: false,
jQueryUI: true,
bProcessing: true,
bServerSide: true,
ajax: {
url: "dataGridQuery.php",
data: { "gridNumber": 2 },
type: 'POST'
},
columns: [
{ title: "Action ID", data: "tblActions.actionID", width: "10%" },
{ title: "Time", data: "tblActions.actionTime" },
{ title: "Action Taken", data: "tblActions.actionTaken" },
{ title: "User", data: "tblUsers.userID" }
]
tableTools: {
sRowSelect: "os",
aButtons: [
{ sExtends: "editor_create", editor: editor1 },
{ sExtends: "editor_edit", editor: editor1 },
{ sExtends: "editor_remove", editor: editor1 }
]
}
});
PHP
// Obtain Action Grid
if(isset($_GET['gridNumber']) && $_GET['gridNumber']==2){
//
$data = Editor::inst( $db, 'tblActions' )
->field(
Field::inst( 'tblActions.actionID' ),
Field::inst( 'tblActions.actionTime' ),
Field::inst( 'tblActions.actionTaken' ),
Field::inst( 'tblActions.actionUserID' ),
Field::inst( 'tblUsers.userID' )
)
->leftJoin( 'tblUsers', 'tblUsers.userID', '=', 'tblActions.actionUserID' )
->process($_POST)
->data();
//
if ( ! isset($_POST['action']) ) {
// Get a list of sites for the `select` list
$data['tblUsers'] = $db
->selectDistinct( 'tblUsers', 'userID as value, userID as label' )
->fetchAll();
}
// Echo
echo json_encode( $data );
}
The errors I receive when running this code are:
Errors {"error":"SQLSTATE[42S22]: Column not found: 1054 Unknown
column 'tblActions.id' in 'field
list'","data":[],"tblUsers":[{"value":"1","label":"1"},{"value":"2","label":"2"}]}
DataTables warning: table id=tblActions - Invalid JSON response. For
more information about this error, please see
http://datatables.net/tn/1.
This code was from a sample provide when downloading the Editor v1.3.1. I am somewhat familiar with the plug-in however find it perplexing when such an error occurs. Any help would be much appreciated.
Thanks :)
You have to change the name of the primary key.
I think if you add the following somewhere.
"idSrc": "actionID",
http://datatables.net/forums/discussion/19199/custom-primary-key
This also may work
$data = Editor::inst( $db, 'tblActions' )
->pkey( 'actionID' )