Initializing Datatables with PHP - php

I am using PHP to generate both the HTML and JS for a set of datatables which each need to have a separate initialization so I can filter different tables separately. As far as I can tell, my code is generating properly, but it appears that my Javascript is not running properly because I do not get any table initialization, and I get a "TypeError: 'undefined' is not a function (evaluating '$('#datatable_0').datatable')" error in the log.
Here is a shortened version of my PHP code ($schedule_options is just an array of times like 9:00 - 10:30 am):
<script src="./js/jquery.dataTables.min.js"></script>
<script src="./js/TableTools.min.js"></script>
<script src="./js/ZeroClipboard.js"></script>
<script type="text/javascript" src="./js/check_in.js.php"></script>
<?php
$counter = 0;
foreach($schedule_options as $option)
{
echo '<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered datatable" id="datatable_' . $counter . '">
<thead>
<tr>
<th>ID</th>
<th>Student Name</th>
<th>Nickname</th>
<th>User Name</th>
<th>Season / Year</th>
<th>Age</th>
<th>Level</th>
<th>Class Time</th>
<th>Instructor</th>
<th>Size</th>
<th>Comments</th>
</tr>
</thead>
</table>';
$counter++;
}
And here is the JS file check_in.js.php:
<?php
Header("content-type: application/x-javascript");
echo '$(document).ready(function() {';
$counter = 0;
foreach($schedule_options as $option)
{
echo 'var datatable_' . $counter . ' = $(\'#datatable_' . $counter . '\').datatable({
"sDom": "<\'row-fluid\'<\'span6\'T><\'span6\'f>r>t<\'row-fluid\'<\'span6\'i><\'span6\'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_ records per page"
},
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "./datatables/students_table.php",
"fnDrawCallback" : function() {
$("[rel=popover]").popover();
},
"oTableTools":
{
"sRowSelect": "single",
"sSwfPath": "./includes/copy_csv_xls_pdf.swf",
"aButtons": [
"copy",
"csv",
"xls",
{
"sExtends": "pdf",
"sTitle": "HSS Students",
"sFileName": "HSS Students.pdf",
"sPdfMessage": "Season: ",
"sPdfOrientation": "landscape"
},
"print"]
}
});
';
$counter++;
}
Thanks for your help. I believe that the main problem I'm having is due to the order of initialization of Javascript or something. I can post full generated code (HTML and JS) if that would help.

Try changing .datatable(...) to .dataTable(...).
JS is case-sensitive :)

Related

issue with getting access to part of URL with jquery and php

im getting issue to access the URL display in the display_table_content.php, to display data into my table content.
It works find if I use the php alone without the jquery and ajax.
display_table_content.php
<input type="hidden" name="job_operation" id="job_operation1" value=""/>
<div id="post_details_data" class="tb_body_container"> </div>
url:display_table_content.php?jobs_name=www
JQUERY _ AJAX
$(document).ready(function(){
fetch_user_data();
function fetch_user_data() {
var job_operation = "fetch";
$.ajax({
url:"get_table_content.php",
method:"POST",
data:{job_operation:job_operation},
success:function(data) {
$('#post_details_data').html(data);
$('#tb_jobs').DataTable({
dom: 'lBfrtip',
responsive: true,
"processing":true,
buttons:[{
extend: 'csv',
exportOptions: {columns: [0, 1, 2, 3, 4]}
},
{
extend: 'pdf',
exportOptions: {columns: [0, 1, 2, 3, 4]}
},
{
extend: 'excel',
exportOptions: {columns: [ 0, 1, 2, 3, 4]}
},
{
extend: 'print',
exportOptions: {columns: [ 0, 1, 2, 3, 4]}
}],
"order":[],
"columnDefs":[{"targets":[0, 3, 4],"orderable":false}]
});
}
});
}
});
get_table_content.php
if(isset($_POST["job_operation"])) {
require_once("database.php");
$pdo = pdo_con();
if ($_POST["job_operation"] == "fetch") {
$user_name= $_GET['jobs_name']; <-- Error seems to be from here
$fetch_data = "SELECT * FROM jobs j WHERE jobs_name = $user_name";
$result_User = $pdo->prepare($fetch_data);
$result_User->execute();
$output = '<table id="tb_jobs" class="table table-bordered table-hover table-striped table-responsive-lg" >
<thead class="thead-dark">
<tr>
<th width="60%">Job Details</th>
<th width="15%">Company Name</th>
</tr>
</thead>';
$output .= '<tbody>';
while ($row = $result_User->fetch(PDO::FETCH_ASSOC)) {
$name_text1= $row['aaa'];
$name_text2= $row['ddd'];
$output .= '
<tr>
<td>' .$name_text1. '</td>
<td>' .$name_text2. '</td>
</tr>';
}
$output .= '</tbody></table>';
echo $output;
}
}
i only the table header are being display, I cannnot fetch the table content due to the 'get' part in the get_table_content.php PHP page
If I have understood waht you want :
This line seems having no sense : $user_name= filter_input(INPUT_GET,"www",FILTER_SANITIZE_STRING); <-- Error seems to be from here
Add in display_table_content.php :
<input type="text" id="job_operation1" value=""/>
<input type="text" id="user_name" value=""/>
<script>
var jobrequest = new Object;
jobrequest.job_operation = $('#job_operation1').val();
jobrequest.user_name = $('#user_name').val();
$.ajax({
url:"get_table_content.php",
method:"POST",
data:jobrequest,
In get_table_content.php :
$job_operation = $_POST["job_operation"];
$user_name = $_POST["user_name"];
If I'm not mistaken you create a HTML table in your back end with php, and then you use DataTables to work with this table you have created, first of all DataTables can use an ajax request to get the content from a json array created in your back end, saying that I think you should do it that way since is more easy to manage for future changes, also it will let the table creation to the front end which is the best aproach, saying that I let you an example to get your table in that way:
Your Html:
<input type="hidden" name="userToFind" id="userToFind" value=""/>
<br>
<button id="btnSearch">Search Operations</button>
<br>
<div class="table-responsive" id="tableOperators" >
<h2>Table Operators</h2>
<table class="display dataTable" id="TablejobOperation" >
<thead>
<tr>
<th>Id</th>
<th>Operation</th>
<th>starts</th>
<th>ends</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>Operation</th>
<th>starts</th>
<th>ends</th>
</tr>
</tfoot>
</table>
</div>
<br>
</div>
your php:
if ($_POST["action"] == "SLC" && isset($_POST["user_name"])) {
$user_name= $_POST["user_name"];
$query = "SELECT * FROM jobs j WHERE jobs_name = $user_name";
$command= $conn->prepare($query);
$command->execute();
$result= $command->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
the DataTable javascript:
var jobOperation= $('#TablejobOperation').DataTable({
"destroy": true,
"responsive":{
"details": {
renderer: function ( api, rowIdx, columns ) {
var data = $.map( columns, function ( col, i ) {
return col.hidden ?
'<tr data-dt-row="'+col.rowIndex+'" data-dt-column="'+col.columnIndex+'">'+
'<td>'+col.title+':'+'</td> '+
'<td>'+col.data+'</td>'+
'</tr>' :
'';
} ).join('');
return data ?$('<table/>').append( data ) :false;
}
}
},
"autoWidth": false,
"ajax": {
"url": 'some.php',
"method": 'POST',
data:{action:"SLC", user_name:username }
},
"columns": [
{"data": "id"},
{"data": "job_operation"},
{"data": "type"},
{"data": "starts"},
{"data": "ends"}
],
"language":{"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"},
"columnDefs": [
{
"className": "dt-center", "targets": "_all"
}
]
});
Your table goes inside a click event:
$("#btnSearch").on('click',function(){
var username = $.trim($('#userToFind').val().replace(/\s+/g, ' '));
var TablejobOperation = $('#tablaSeguros').DataTable();
if ($.fn.DataTable.isDataTable("#TablejobOperation")) {
TablejobOperation.destroy();
$('#TablejobOperationtbody').remove();
}
//the datatable script from the top goes here
})
Hope it helps

DataTable AjaxSource

I'm going straight to the point here.
what I am trying to accomplish is to populate the table using ajax.
this gives me jquery.dataTables.min.js:39 Uncaught TypeError: Cannot read property 'length' of undefined error.
here's my code:
my php code:
public function pending_data(){
$result = $this->ticketing_m->get_pending_tickets();
echo json_encode($result);
}
JQUERY
var datatable = $("#datatable");
datatable.DataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": datatable.data('url')
});
HTML
<table id="datatable" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%" data-url="<?php echo site_url(array("dashboard","pending_data")); ?>">
<thead>
<tr>
<th>Ticket Number</th>
<th>Subject</th>
<th>From</th>
<th>Date Created</th>
</tr>
</thead>
</table>
QUERY RESULT
First off, you should probably set bServerSide to false. If it is true you need to actually read the request parameters, do server side processing and structure your return data as outlined in the Server-side processing documentation. Since you are doing none of those things here I'm assuming you simply want to use Ajax sourced data and let the DataTables javascript handle the table processing
Next, structure your json with the table data inside data as shown here in example #2. Your json should look something like this:
{
"data": [
{
"date_created": "2017-06-13 13:57:24",
"full_name": "John Doe",
"subject": "Test",
"ticket_number": "Ticket 1234"
},
...
]
}
To accomplish this you might do something as simple as this in the response from pending_data():
echo json_encode(array('data' => $result));
Also, the way you have your DataTables properties set up here looks like you are either using a very old version or an outdated syntax. I'd suggest installing the latest version and using up to date code. You can get all the downloads and examples you might need at: https://datatables.net
I think your ajax source has 4 columns.
But you have 5 columns in < thead >.
Pls remove one tag in < thead >.
<table id="datatable" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%" data-url="<?php echo site_url(array("dashboard","pending_data")); ?>">
<thead>
<tr>
<th>Ticket Number</th>
<th>Subject</th>
<th>From</th>
<th>Date Created</th>
</tr>
</thead>
</table>
var oTable = $('#datatable').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "${pageContext.request.contextPath}/",
"aoColumns" : [
{ "mData": "Ticket Numbe" },
{ "mData": "Subject" },
{ "mData": "From" },
{ "mData": "Date Created" }
]
});
I don't get the exact problem.This may help..
Do something like that also use data type https://datatables.net/examples/server_side/jsonp.html
"processing": true,
"serverSide": true,
"ajax": {
"url": "scripts/jsonp.php",
"dataType": "jsonp"
}
Use it like:
var url = 'http://www.json-generator.com/api/json/get/cbEfqLwFaq?indent=2';
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
type: 'POST',
'url': url,
'data': function (d) {
console.log(d.order);
return JSON.stringify( d );
}
}
});
Working Fiddle

datatable pagination work for first paginate only

I am trying to paginate my data with data table plugin but its pagination works for the first time only. first, its loads showing data when I click on the second page it works but after that, it doesn't. it shows processing on the top of the table here is my code.
HTML
<table id="data_table" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th><input type="checkbox" id="selectAll"/></th>
<th>Plan Name</th>
<th>Description</th>
<th>Image</th>
<th>Quantity</th>
<th>Amount</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
JQUERY
$("#data_table").dataTable({
"bProcessing": true,
"bServerSide": true,
"bPaginate": true,
"sAjaxSource": "response.php",
});
PHP
if(isset($_GET['iDisplayStart']))
{
$start = $_GET['iDisplayStart'];
}
else
{
$start = 0;
}
if(isset($_GET['iDisplayLength']))
{
$limit = $_GET['iDisplayLength'];
}
else
{
$limit = 10;
}
$plan = new Plan();
$result = $plan->getPlanList($limit, $start);
$count= $plan->getCountPlanList();
$myarray['recordsTotal'] = $count[0]['count(*)'];
$myarray['recordsFiltered'] = $count[0]['count(*)'];
$myarray['draw'] = intval($start/$limit)+1;
$myarray['data'] ="";
foreach($result as $data)
{
$myarray['data'][] = array('<input type="checkbox" name="selectcheck[]" class="selectcheck" value="'.$data['id'].'">',$data['name'],$data['description'],$data['image'],$data['quantity'],$data['amount'],'Edit');
}
echo json_encode($myarray);
die;
problem solved. I use sEcho value for draw on server side
$myarray['draw'] = $_GET['sEcho'];

Laravel 4 Datatable Integration

I am new in Laravel and I want to generate MYSQL data using Laravel datatable, I did as follow:
This is my html table for generating datatables:
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-condensed table-bordered" id="articles">
<thead>
<tr>
<th>ID</th>
<th>Code</th>
<th>Name</th>
<th>Description</th>
<th>Created At</th>
<th>Updated At</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
And this is my js:
<script type="text/javascript">
$('#articles').dataTable(
{
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "{{URL::to('arayez/getView')}}",
"aaSorting": [[ 3, "desc" ]],
"aoColumns": [
{ 'sWidth': '60px' },
{ 'sWidth': '130px', 'sClass': 'center' },
{ 'sWidth': '180px', 'sClass': 'center' },
{ 'sWidth': '60px', 'sClass': 'center' },
{ 'sWidth': '90px', 'sClass': 'center' },
{ 'sWidth': '80px', 'sClass': 'center' },
{ 'sWidth': '80px', 'sClass': 'center' }
]
}
);
</script>
And this is my controller function:
class Test extends BaseController
{
public function getView()
{
$result = DB::table('module')->select(array('module.id AS id','module.code','module.name','module.description','module.created_at','module.updated_at','module.user_id'));
return Datatables::of($result)->make();
}
}
And this is my route:
Route::group(
array('prefix' => 'arayez'),
function() {
Route::get('test', 'arayez\Test#getTest');
Route::get('getView', array('uses'=>'arayez\Test#getView','as'=>'arayezGetView'));
}
);
And this is the error:
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"syntax error, unexpected '['","file":"\/var\/www\/auth\/vendor\/bllim\/datatables\/src\/Bllim\/Datatables\/Datatables.php","line":79}}
Is some thing wrong with my code?
Thanks for your helping.
Looking at the file in the error message (View on github) you can see that it's just a short array syntax added in PHP 5.4. Here's an example:
$array = []; // instead of $array = array();
This error almost certainly means that your PHP version is older than 5.4. The only way to fix this is to upgrade PHP to at least 5.4. Especially since it's also a requirement for Laravel (I believe since version 4.1)

TypeError: oColumn is undefined When Using jQuery Datatables Library

I am having a problem getting the jQuery Datatables library to show up properly on my Joomla website table.
http://datatables.net
The script is half styling my table and then giving up (I am getting the table header colour changed and text colour, but no datatables controls etc).
Firebug is also throwing the following error:
TypeError: oColumn is undefined
In my Joomla templates index.php I have the following in the <head>:
<script src="./datatables/js/jquery.js" type="text/javascript"></script>
<script src="./datatables/js/jquery.dataTables.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function() {
jQuery('#staff_table').dataTable({
"bLengthChange": true,
"bFilter": true,
"bSort": true,
"bInfo": true,
"bAutoWidth": true
} );
} );
</script>
The HTML / PHP looks like this:
<h3>Members of Staff</h3>
<p>If you're looking for a member of staff at Tower Road Academy, you'll find their details here.</p>
<table class="staff_table" id="staff_table">
<tr class="staff_table_head">
<th>Name</th>
<th>Job Title</th>
<th>Email Address</th>
</tr>
<?php
$result = mysql_query("SELECT * FROM itsnb_chronoforms_data_addstaffmember");
while($row = mysql_fetch_array($result))
{
echo '<tr>';
echo '<td>' . $row['staff_name'] . '</td><td>' . $row['staff_job'] . '</td><td>' . $row['staff_email'] . '' . '</td>';
echo '</tr>';
}
?>
</table>
For datatable to work properly, your tables must be constructed with a proper <thead> and <tbody> tags.
All DataTables needs in your HTML is a <TABLE> which is well formed (i.e. valid HTML), with a header (defined by a <THEAD> HTML tag) and a body (a <TBODY> tag)
Datatable docs
Sorted it !, it turns out datatables is VERY strict about the html it accepts before it throws an error. I added tags to my html and now it is working, also note that you must have tags for your header columns and not tags as this also throws an error.
The html code now looks like this :
<h3>Members of Staff</h3>
<p>If you're looking for a member of staff at Tower Road Academy, you'll find their details here.</p>
<table class="staff_table" id="staff_table">
<thead>
<tr class="staff_table_head">
<th>Name</th>
<th>Job Title</th>
<th>Email Address</th>
</tr>
</thead>
<?php
$result = mysql_query("SELECT * FROM itsnb_chronoforms_data_addstaffmember");
while($row = mysql_fetch_array($result))
{
echo '<tr>';
echo '<td>' . $row['staff_name'] . '</td><td>' . $row['staff_job'] . '</td><td>' . $row['staff_email'] . '' . '</td>';
echo '</tr>';
}
?>
</table>
and calling the jquery etc looks like this :
<script src="./datatables/js/jquery.js" type="text/javascript"></script>
<script src="./datatables/js/jquery.dataTables.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#staff_table').dataTable({
"bLengthChange": true,
"bFilter": true,
"bSort": true,
"bInfo": true,
"bAutoWidth": true
} );
} );
</script>
Hope this would help you all, at least to get a hint out of it.
http://datatables.net/forums/discussion/comment/42607
My problem was, TypeError: col is undefined.
Summarized Answer:
Number of TH elements within the TR element within the THead
element of the Table MUST BE EQUAL to the Number of TD elements(or
number of columns within your Table Rows) within the TR element(s) of
your TBody in the Table.
You can read the explanation bellow:
The problem was, I hadn't put enough Th or Td elements within the thead section to be equal to the number of columns which I print as Td elements inside the Tr elements within the TBody section.
Following code did give me the error.
<thead>
<tr>
<th> Heading 1</th>
<th> Heading 2</th>
</tr>
</thead>
<tbody>
<tr>
<td> Column 1 </td>
<td> Column 2</td>
<td> Column 3</td>
</tr>
</tbody>"
But just adding one more Th element to the Tr element within the THead element made it works like a charm! :) And I got the hint from the above link.
And also, I found that all the TH elements within the THead's Tr element could be TD elements too, as it's also valid HTML to the required level by the jQuery DataTables!
Hope I helped some of you to save your time! :)
Try this:
jQuery('#staff_table').dataTable({
"bPaginate": true,
"bLengthChange": true,
"bFilter": true,
"bSort": true,
"bInfo": true,
"bAutoWidth": true,
"aoColumns": [
null,
null //put as many null values as your columns
]
});

Categories