Server Side Ajax Datatables - php

I am executing serverside datatables and im getting this kind of error
TypeError: c is undefined
...iRecordsDisplay=parseInt(f,10);d=0;for(e=c.length;d<e;d++)N(a,c[d]);a.aiDisplay=...
this is my server side,
require_once '../../resources/db.config.php';
$db = DATABASE::instance();
$mysqli = $db->get();
$result = $mysqli->query("SELECT * FROM mst_product");
$rows = array();
while( $r = $result->fetch_assoc() ){
$rows[] = $r ;
}
header('Content-type: application/json');
echo json_encode($rows, JSON_PRETTY_PRINT);
and my datatables
<table id="productlist" class="table">
<thead>
<tr>
<th>No</th>
<th>SKU</th>
<th>Product Description</th>
<th>Product Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
$(function () {
$("#productlist").DataTable({
"destroy": true,
"processing": true,
"serverSide": true,
"ajax": {
"url": "../../../html/data/productlist.php",
"type": "POST"
},
"columns": [
{ "data": "prod_id" },
{ "data": "prod_sku" },
{ "data": "prod_desc" },
{ "data": "prod_prc_idr" }
]
});
});
</script>
and my imports,
<!-- DATA TABLES -->
<link href="../../library/plugins/datatables/media/css/dataTables.bootstrap.min.css" rel="stylesheet" type="text/css"/>
<!-- DATATABLES -->
<script src="../../library/plugins/datatables/media/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="../../library/plugins/datatables/media/js/dataTables.bootstrap.min.js" type="text/javascript"></script>
please help me i dont know where i am doing wrong .... JSON data service is fine...

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();

datatables "No data available in table"

This isn't my first time using datatables, but I have an implementation that I can't seem to get to work.
PHP:
public function renderTable() {
$config = $this->container->get('RestorePoint\Configuration');
$displayAndRestoreFrom = $config->get('Settings.displayAndRestoreFrom');
if ($displayAndRestoreFrom !== 'local') {
$remoteStorage = $this->container->get('RestorePoint\RemoteFilesystemFactory');
$service = $remoteStorage->service($displayAndRestoreFrom);
$files = $service->listFilesByCreated($service->getFolder());
} else {
$files = $this->getFilesByCreated($config->get('dir.files'));
}
foreach ($files as &$file) {
if ($displayAndRestoreFrom == 'local') {
$file['id'] = $file['name'];
}
$file['adapter'] = $displayAndRestoreFrom;
$file['created'] = date('Y-m-d H:i:s', $file['created']);
$file['actions'] = '';//view('RestorePoint.actions')->with($file)->render();
}
//echo json_encode(array('data'=>$files), JSON_UNESCAPED_SLASHES);
return response()->json($files);
}
HTML:
<div class="table-responsive">
<table class="table card-table table-vcenter text-nowrap datatable" id="backups" role="grid">
<thead>
<tr>
<td class="w01">Name</td>
<td>Created</td>
<td>Adapter</td>
<td>Actions</td>
</tr>
</thead>
</table>
</div>
JS: (defined in head)
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="./assets/plugins/datatables/datatables.min.js"></script>
<script>
$(document).ready(function () {
$('#backups').DataTable({
//"deferRender": true,
ajax: {
url: "<?php echo url('restorepoint/renderTable'); ?>",
dataSrc: ''
},
columns: [
{data: 'name'},
{data: 'created'},
{data: 'adapter'},
{data: 'actions'}
]
});
});
</script>
JSON:
{"5":{"name":"restorepoint_2019_08_02_05_47_49.zip","id":"\/restore_point_backups_fagardesignscom\/restorepoint_2019_08_02_05_47_49.zip","created":"2019-08-02 05:55:11","adapter":"dropbox","actions":""},"4":{"name":"restorepoint_2019_08_02_07_30_05.zip","id":"\/restore_point_backups_fagardesignscom\/restorepoint_2019_08_02_07_30_05.zip","created":"2019-08-02 03:36:59","adapter":"dropbox","actions":""},"3":{"name":"restorepoint_2019_08_02_07_32_57.zip","id":"\/restore_point_backups_fagardesignscom\/restorepoint_2019_08_02_07_32_57.zip","created":"2019-08-02 03:35:54","adapter":"dropbox","actions":""},"2":{"name":"restorepoint_2019_08_02_07_38_55.zip","id":"\/restore_point_backups_fagardesignscom\/restorepoint_2019_08_02_07_38_55.zip","created":"2019-08-02 03:34:46","adapter":"dropbox","actions":""},"1":{"name":"restorepoint_2019_08_02_08_13_49.zip","id":"\/restore_point_backups_fagardesignscom\/restorepoint_2019_08_02_08_13_49.zip","created":"2019-08-02 03:33:40","adapter":"dropbox","actions":""},"0":{"name":"restorepoint_2019_07_31_08_10_34.zip","id":"\/restore_point_backups_fagardesignscom\/restorepoint_2019_07_31_08_10_34.zip","created":"2019-07-31 03:54:27","adapter":"dropbox","actions":""}}
Datatables is showing "No data available in table" however, I don't understand why given I've followed this example: https://datatables.net/examples/ajax/custom_data_flat.html
it was the indexes messing things up.
needed to use array_values()
return response()->json(array_values($files));

Using AJAX to insert data but Datatable shows no result

I want to use AJAX to load data from database and display it using DataTable. The database is loaded and can be seen, but the Datatable shows:
Showing 0 to 0 of 0 entries (filtered from NaN total entries)
<table id="employee_data" class="table table-striped table-bordered">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Department</td>
<td>Job Title</td>
<td>Employee Type</td>
<td>Employee Status</td>
</tr>
</thead>
</table>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$('#employee_data').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"searching" : true,
"ajax" : {
url: 'employeeData.php',
type: "post",
dataType: "json",
contentType: "application/json; charset=utf-8"
},
"columns": [
{ "data": "eId"},
{ "data": "eName"},
{ "data": "eDepartment"},
{ "data": "eJobTitle"},
{ "data": "eEmployeeType"},
{ "data": "eEmployeeStatus"}
]
} );
});
</script>
employeeData.php
$query ="
SELECT *
FROM employee
ORDER BY employeeID DESC";
$result = mysqli_query($link, $query);
$data = array();
while($row=mysqli_fetch_array($result))
{
$data['data'][] = array(
'eId' => $row['employeeId'],
'eName' => $row['employeeLastName'],
'eDepartment' => $row['department'],
'eJobTitle' => $row['jobTitle'],
'eEmployeeType' => $row['employeeType'],
'eEmployeeStatus' => $row['employeeStatus']
);
}
echo json_encode($data);

Why html loads completely before loading datatable?

For downloading button I had refer page:
https://www.datatables.net/extensions/buttons/examples/initialisation/export.html
For server side I had refer page:
https://datatables.net/examples/data_sources/server_side.html
I had refer above page for making datatable to get data from database and download in different format. But the main problem is it first load the html table. after completely loading html table it shows the datatable which is noticeable for large no of rows. I have to get large no of rows to show in datatable and export the file in excel. Can anyone help me how can i load datatable without loading html table.
Here is my code
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- for button -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.3.1/css/buttons.dataTables.min.css">
<!-- for button -->
</head>
<body>
<table id="example" class="display nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th style="text-align: center;">Model No</th>
<th style="text-align: center;">BIll NO</th>
<th style="text-align: center;">Name Of Party</th>
<th style="text-align: center;">Bill Miti</th>
<th style="text-align: center;">Invoice Date</th>
<th style="text-align: center;">IMEI No</th>
<th style="text-align: center;">Price</th>
<th style="text-align: center;"><div id="section_notTo_Print"> Edit </div></th>
</tr>
</thead>
<tbody>
<?php
include 'dbconnect.php';
//get records from database
$query = $con->query("SELECT * FROM salesreport ORDER BY id DESC");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){ ?>
<tr>
<td style="text-align: center;"><?php echo $row['modelno']; ?></td>
<td style="text-align: center;"><?php echo $row['billno']; ?></td>
<td style="text-align: center;"><?php echo $row['nameOfParty']; ?></td>
<td style="text-align: center;"><?php echo $row['billMiti']; ?></td>
<td style="text-align: center;"><?php echo $row['invoiceDate']; ?></td>
<td style="text-align: center;"><?php echo $row['IMEINo']; ?></td>
<td style="text-align: center;"><?php echo $row['price']; ?></td>
<td style="text-align: center;"><div id="section_notTo_Print"> Edit </div></td>
<!-- <td><?php //echo $row['Quantity']; ?></td> -->
<!-- <td><?php //echo ($row['status'] == '1')?'Active':'Inactive'; ?></td> -->
</tr>
<?php } }else{ ?>
<tr><td colspan="5">No distributor found.....</td></tr>
<?php } ?>
</tbody>
</table>
<!-- for exporting -->
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.3.1/js/dataTables.buttons.min.js">
</script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/pdfmake.min.js">
</script>
<script type="text/javascript" src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/vfs_fonts.js">
</script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.print.min.js"></script>
<script>
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
// "serverSide": true,
// "ajax": "datatable2.php",
dom: 'lBfrtip',
buttons: [
{
extend: 'collection',
text: 'Export',
buttons: [
'copy',
'excel',
'csv',
'pdf',
'print'
]
}
]
} );
} );
</script>
<!-- for exporting -->
</body>
</html>
This code for your reference it`s sample code how to load table record from database in datatable
Viewfile
<table id="placeTable" class="table table-striped table-bordered responsive nowrap">
<thead class="">
<tr>
<th>Name</th>
<th>Location</th>
<th>Status</th>
<th>Action</th>
<th></th>
</tr>
</thead>
</table>
</div><!--table-responsive-->
<script>
jQuery(document).ready(function () {
jQuery('#placeTable').DataTable({
"oLanguage": {
"sProcessing": '<img alt src="<?php echo base_url('assets/images/loaders/CustomLoader.gif'); ?>" style="opacity: 1.0;filter: alpha(opacity=100);">'
},
"processing": true,
"serverSide": true,
"responsive": true,
"order": [[4, "DESC"]],
"ajax": {
url: "<?php echo site_url('admin/place/getPlace'); ?>",
},
"columns": [
{"taregts": 0, "data": "name"},
{"taregts": 1, "data": "location"},
{"taregts": 2,
"searchable": false,
"orderable": false,
"sClass": "text-center",
"render": function (data, type, row) {
var id = row.id;
if (row.is_active === '1') {
var out = ' <a class="btn btn-success statusenable" href="#" \n\ \n\
title="Click to Change status" data-href="<?php echo site_url('admin/place/change_status') ?>/' + id + '" data-toggle="modal" data-target="#confirm-status" title="Confirm">\n\
Enable</i></a> ';
return out;
} else if (row.is_active === '0') {
var out = ' <a class="btn btn-danger statusenable" href="#" \n\ \n\
title="Click to Change status" data-href="<?php echo site_url('admin/place/change_status') ?>/' + id + '" data-toggle="modal" data-target="#confirm-status" title="Confirm">\n\
Disable</i></a> ';
return out;
}
}
},
{"taregts": 3, "searchable": false,
"orderable": false,
"sClass": "text-center",
"render": function (data, type, row) {
var id = row.id;
return '<a class="actioncol cursor view" href=\'<?php echo site_url('admin/place/view'); ?>/' + id + '\'\n\
title="View"><i class="glyphicon glyphicon-eye-open"></i></a>\n\<a class="actioncol cursor view" href=\'<?php echo site_url('admin/place/edit'); ?>/' + id + '\'\n\
title="Edit"><i class="glyphicon glyphicon-edit"></i></a>';
}
},
{"taregts": 4, "visible": false,
render: function (data, type, row) {
return row.id;
}
}
]
});
});
</script>
Controller Place.php file
//get all place
public function getPlace() {
$columns = array('name', 'location','is_active','id','id');
$request = $this->input->get();
$condition = array();
$getfiled = "name,is_active,location,id";
echo $this->db_common->getDataTableSource('place', $columns, $condition, $getfiled, $request);
die();
}
model for database query common.php
/*
* This function is to create the data source of the Jquery Datatable
*
* #param $tablename Name of the Table in database
* #param $datatable_fields Fields in datatable that avalable for filtering
* #param $condition_array conditions for Query
* #param $data The field set tobe return to datatables
* #param $request The Get or Post Request Sent from Datatable
* #param $join_str Join array for Query
* #return JSON data for datatable
*/
function getDataTableSource($tablename, $datatable_fields = array(), $conditions_array = array(), $data = '*', $request, $join_str = array()) {
$output = array();
//Fields tobe display in datatable
$this->db->select($data);
//Making Join with tables if provided
if (!empty($join_str)) {
foreach ($join_str as $join) {
if (!isset($join['join_type'])) {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id']);
} else {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id'], $join['join_type']);
}
}
}
//COnditions for Query
if (!empty($conditions_array)) {
$this->db->where($conditions_array);
}
//Total record in query tobe return
$output['recordsTotal'] = $this->db->count_all_results($tablename, FALSE);
//Filtering based on the datatable_fileds
if ($request['search']['value'] != '') {
$this->db->group_start();
for ($i = 0; $i < count($datatable_fields); $i++) {
if ($request['columns'][$i]['searchable'] == true) {
$this->db->or_like($datatable_fields[$i], $request['search']['value']);
}
}
$this->db->group_end();
}
//Total number of records return after filtering not no of record display on page.
//It must be counted before limiting the resultset.
$output['recordsFiltered'] = $this->db->count_all_results(NULL, FALSE);
//Setting Limit for Paging
$this->db->limit($request['length'], $request['start']);
//ordering the query
if (isset($request['order']) && count($request['order'])) {
for ($i = 0; $i < count($request['order']); $i++) {
if ($request['columns'][$request['order'][$i]['column']]['orderable'] == true) {
$this->db->order_by($datatable_fields[$request['order'][$i]['column']] . ' ' . $request['order'][$i]['dir']);
}
}
}
$query = $this->db->get();
$output['draw'] = $request['draw'];
$output['data'] = $query->result_array();
return json_encode($output);
}`enter code here`

ajax jquery datatable not return datas on table

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.

Categories