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)
Related
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();
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
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
I am using jquery datatable use it from external cdn
<script src="http://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
and my table is
<table class="table table-bordered data-table" id="blocked_list">
<thead>
<tr>
<th>User Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
</table>
and cal this in jquery function
#section('script')
<script>
$('#blocked_list').DataTable({
"ajax": "{{ route('user.sold_products') }}",
"columns": [
{ data: 'id' },
{ data: 'buyer_id'},
{ data: 'seller_id' },
]
});
</script>
#endsection
here i think i done correctly but the data not displayed inside my table and i call data from my controller is:
public function all(){
$user = Auth::user();
$block = Block::all();
$bl = Block::where('buyer_id',$user->id)->get();
return Response::json([
'data' => $block
], 200);
}
my controler having following values inside data variable
{"data":[{"id":1,"seller_id":12,"buyer_id":11,"email":"","created_at":"2017-06-01 11:37:54","updated_at":"2017-06-01 11:37:54"},{"id":2,"seller_id":10,"buyer_id":11,"email":"","created_at":"2017-06-01 14:20:51","updated_at":"2017-06-01 14:20:51"}]}
when thevalues not displayed inside myy laravel table i doknow why can anyone please help to solve this issue.
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 :)