DataTable AjaxSource - php

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

Related

Record is not loading to the Datatable using php ajax

i am creating the simple crud system using php. when i load the to the datatable data is not loading.when i show the error on console Uncaught TypeError: Cannot read property 'length' of undefined
i am tring to solve out this problem since yesterday but i couldn't
Table
<table id="tbl-category" class="table table-responsive table-bordered" cellspacing="0"
width="100%">
<caption> Products</caption>
<thead>
<tr>
<th>Patient No</th>
<th>Name</th>
<th>Phone</th>
<th>Address</th>
</tr>
</table>
jQuery
function get_all() {
$('#tbl-category').dataTable().fnDestroy();
var oTable = $('#tbl-category').DataTable({
"ajax": {
"url": 'all_category.php',
"type": "get",
"datatype": "json"
},
"columns": [
{ "data": "patientno" },
{ "data": "name" },
{ "data": "phone" },
{ "data": "address" },
]
})
}
all_category.php Page
<?php
include("db.php");
$stmt = $conn->prepare("select patientno,name,phone,address from patient order by patientno DESC ");
if ($stmt->execute()) {
$stmt->bind_result($patientno,$name,$phone,$address);
while ( $stmt->fetch() ) {
$output[] = array ("patientno"=>$patientno, "name"=>$name,"phone"=>$phone,"address"=>$address);
}
echo json_encode( $output );
}
$stmt->close();

Ajax based search - how to put results into datatables

I am trying to make ajax based search but i am very new in javascript and ajax. I need sorting, filtering etc. for results so i put results into Datatables.
First of all i'am using standard html form input (it is main search field):
<input type="text" class="form-control" formmethod="post" oninput="return delayExecute();" id="name" name="name" size="61" autofocus/>
It calls delayExecute() function when user put something into form. Next, one second after user is finished writing the script run ajax request. Script looks like that:
<script>
var typingTimer;
var doneTypingInterval = 700;
function delayExecute()
{
clearTimeout(typingTimer);
typingTimer = setTimeout(
function(){makeAjaxRequest(name)},
1000
);
return true;
}
function makeAjaxRequest(name) {
$('#loading')
.show()
var myrequest = $.ajax({
url: 'ajax_search',
type: 'post',
data: {name: $('input#name').val()},
ajaxSend: function() {
},
success: function(response) {
$('table#dataTables-example tbody').html(response);
},
complete:function(){
//
$('#loading')
.hide();
$('#dataTables-example').dataTable({
// "destroy": true,
"processing": true,
"aaSorting": [],
"iDisplayLength": 10,
"aLengthMenu":[[10, 15, 25, 35, 50, 100, -1], [10, 15, 25, 35, 50, 100, "All"]]
}).columnFilter(
{
aoColumns: [
{type: "null"},
{sSelector: "#mag_filter_column", type: "select"},
]
}
);
}
});
};
In Php file (ajax_request) i read data from data base. Next I use echo function to put things into table like that:
echo '<tr>';
echo '<td>'.$some_variable.'</td>';
echo '<td>'.$other_variable.'</td>';
echo '</tr>;
And table in the view looks like that:
<table class="main-search table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Col</th>
<th>War</th>
<th>Symbol</th>
<th>Name</th>
<th>Quantity</th>
<th>Descripion</th>
<th>Photo</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
This whole thing almost work. When i make search for the first time it loads everything into datatable and everything works good (pagination, sorting etc). But when i do second search (change some word for example) - ajax serch runs, it find something but the data doesn't load into datatable. I think that i need to find way to refresh datatable plugin. I tried to use datatable.clear(), datatable.destroy() and couple other things but nothing works well for me. What is the right way to do it?
My datatable plugin version: DataTables 1.10.5
jquery version: 2.1.1

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)

Initializing Datatables with 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 :)

DataTables: #example working but #datatable not working when making AJAX call

I want to know the difference between #example and #datatable. I have seen one example there they are using one table with div id as datatable using some hardcoded value. And another table with div id as example . I can make a Ajax call for that second example. But i cant do it for first one.
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#example').dataTable( {
"bProcessing": true,
"sAjaxSource": "Json/CustomerListJson.php",
"sScrollX": "70%",
"sScrollXInner": "110%",
"bScrollCollapse": true
} );
} );
</script>
The above code is working well.
But If i change the table id to datatable like
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#datatable').dataTable( {
"bProcessing": true,
"sAjaxSource": "Json/CustomerListJson.php",
"sScrollX": "70%",
"sScrollXInner": "110%",
"bScrollCollapse": true
} );
} );
</script>
<div id="dynamic">
<table cellpadding="0" cellspacing="0" border="0" class="display dataTable" id="datatable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Contact</th>
<th>Email</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Country</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
I got one warning pop alert which says
DataTables warning (table id = 'datatable'): Cannot reinitialise DataTable.
To retrieve the DataTables object for this table, pass no arguments or see the docs for bRetrieve and bDestroy.
This is my first project using Bootstrap CSS.
Please provide me the best way.
I want this type of look and feel.
But I got this type of table.
Finally I got this error message, if i use #datatable
DataTables warning (table id = 'datatable'): Cannot reinitialise DataTable.
To retrieve the DataTables object for this table, pass no arguments or see the docs for bRetrieve and bDestroy
You will get a warning when you initialize same datatable twice. Check this example. Using an example given in the datatable docs i was able to apply Bootstrap css. Check the same fiddle link.
If for some reason you are not able to remove the second datatable call, set bDestroy to true link this example or check this link $("#tableId").dataTable().fnDestroy();.
$('#example').dataTable({
"sScrollY": "200px",
"bPaginate": false
});
// Some time later....
$('#example').dataTable({
"bFilter": false,
"bDestroy": true //<-- set bDestroy to true which will destroy the previous initializarion
});
Change this
var oTable = $('#datatable').dataTable( {
"bProcessing": true,
"sAjaxSource": "Json/CustomerListJson.php",
"sScrollX": "70%",
"sScrollXInner": "110%",
"bScrollCollapse": true
} );
to
var oTable = $('#datatable').dataTable( {
"bProcessing": true,
"sAjaxSource": "Json/CustomerListJson.php",
"sScrollX": "70%",
"sScrollXInner": "110%",
"bScrollCollapse": true,
"bDestroy": true,
"bJQueryUI": true
} );

Categories