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' )
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
Here is all the code related to the #results table:
jQuery(document).ready(function) {
editor = new jQuery.fn.dataTable.Editor( {
ajax: "<?php echo $full_dir . '/ajax_call.php'; ?>",
table: "#results",
fields: [ {
label: "Mfg ID",
name: "ball_mfg.mfgID"
}, {
label: "Mfg name:",
name: "ball_mfg.name"
}, {
label: "Model #",
name: "ball_model.modelID"
}, {
label: "Model Name:",
name: "ball_model.name"
}
]
} );
jQuery('#results').DataTable( {
"pagingType": "full_numbers",
dom: "Bfrtip",
ajax: {
url: "<?php echo $full_dir . '/ajax_call.php'; ?>",
type: 'POST'
},
columns: [
{ "render": function ( data, type, full, meta ) {
return '<input type="radio" name="select_model" class="radio1 my_input" data-modelID="'+full.ball_model.modelID+'">';
}}, // here's a radio button, modify to use data to populate it,
{ data: "ball_mfg.name" },
{ data: "ball_model.name" }
],
select: false,
buttons: [
]
} );
This only displays the standard Previous, page numbers and Next button. You can view the output at https://www.bowling-tracker.com/bowl/bowling-resources/bowling-ball-information
My preference would actually be to have an input box. You'll note that I have
<script type="text/javascript" src="https://cdn.datatables.net/plug-ins/1.10.16/pagination/input.js"></script>
in the header and I've tried to use
"pagingType":"input",
as well but it doesn't seem to matter which paging Type that I use, it simply does not change the pagination buttons.
I'm using DataTables Editor to generate this because it needs to be run on the server side (due to returned results) and so I can display only a few tables (which are joined).
Look at the source code that loads. There is no "pagingType". Change it to input so we can see the output when it is written correctly.
Need to add label for payment_type based on the condition if status "2" then "Cash" and for "1" - credit.
photo
This my javascript code:
/*
* Editor client script for DB table odenis
* Created by http://editor.datatables.net/generator
*/
(function($){
$(document).ready(function() {
var editor = new $.fn.dataTable.Editor( {
ajax: 'php/table.odenis.php',
table: '#odenis',
fields: [
{
"label": "Öd\u0259ni\u015f üsulu:",
"name": "usul",
"type": "radio",
"options": [
{ label: "Nəğd", value: "1" },
{ label: "Kontur", value: "2" }
//"1" ,
//"2"
]
},
{
"label": "Öd\u0259ni\u015f müdd\u0259ti:",
"name": "muddet",
"type": "radio",
"options": [
{ label: "Aylıq", value: "1" },
{ label: "Yığılsın deyərəm", value: "2" },
{ label: "10 günlük", value: "3" },
{ label: "Həftəlik", value: "4" },
{ label: "15 günlük", value: "5" }
]
},
{
"label": "Öd\u0259ni\u015f tarixi:",
"name": "tarix",
"type": "datetime",
"format": "YYYY-MM-DD"
},
{
"label": "Öd\u0259ni\u015f miqdar\u0131:",
"name": "miqdar"
}
]
} );
var table = $('#odenis').DataTable( {
dom: 'Bfrtip',
ajax: 'php/table.odenis.php',
columns: [
{
"data": "usul",
},
{
"data": "muddet"
},
{
"data": "tarix"
},
{
"data": "miqdar"
}
],
select: true,
lengthChange: false,
buttons: [
{ extend: 'edit', editor: editor },
{ extend: 'remove', editor: editor }
]
} );
} );
}(jQuery));
and this is php:
<?php
$cariid = file_get_contents('../../cariid.txt');
/*
* Editor server script for DB table odenis
* Created by http://editor.datatables.net/generator
*/
// DataTables PHP library and database connection
include( "lib/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;
// The following statement can be removed after the first run (i.e. the database
// table has been created). It is a good idea to do this to help improve
// performance.
$db->sql( "CREATE TABLE IF NOT EXISTS `odenis` (
`id` int(10) NOT NULL auto_increment,
`obyekt_id` varchar(255),
`usul` varchar(255),
`muddet` varchar(255),
`tarix` date,
`miqdar` varchar(255),
PRIMARY KEY( `id` )
);" );
// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'odenis', 'id' )
->fields(
Field::inst( 'obyekt_id' )
->set( false ),
Field::inst( 'usul' )
->validator( 'Validate::notEmpty' ),
Field::inst( 'muddet' )
->validator( 'Validate::notEmpty' ),
Field::inst( 'tarix' )
->validator( 'Validate::notEmpty' )
->validator( 'Validate::dateFormat', array( 'format'=>'Y-m-d' ) )
->getFormatter( 'Format::date_sql_to_format', 'Y-m-d' )
->setFormatter( 'Format::date_format_to_sql', 'Y-m-d' ),
Field::inst( 'miqdar' )
->validator( 'Validate::notEmpty' )
)
->where( 'obyekt_id', $cariid )
->process( $_POST )
->json();
working fine in edit button(picture 2). But i need it in table also.
enter image description here
İ solved by using render.
data:"usul",
render:function ( data, type, row ) {
var melumat = data;
if((type === "display" || type === "filter") && melumat ==1){
return 'Nəğd';
}
else if((type === "display" || type === "filter") && melumat ==2){
return 'Kontur';
}
else{
return data;
}
}
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.
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();
}
}
]
} );
}