I am trying to get a dataTable on a page called "locations.php" but i am still get a JSON invalid error.
I generate the JSON dynamically using this php code on "get_SR_Locations.php":
$myjson = array();
foreach ($locationList as $list) :
$json= array(
"id" => addslashes($list['id']),
"name" => addslashes($list['name']),
"address" => addslashes($list['address']),
"telephone" => addslashes($list['telephone']),
"emailaddress" => addslashes($list['email'])
);
array_push($myjson, $json);
endforeach;
$mj=array("data"=>$myjson);
echo json_encode($mj);
The generated JSON looks something like this:
{"data":[{"id":"108","name":"Sportpark","address":"Karspstreet 501","telephone":"0123456789","emailaddress":"sport#mail.com"},{"id":"2","name":"Blaashal","address":"Gustavstreet 2920","telephone":"","emailaddress":"sporting#mailing.com"}]}
So when I put this in a JSON validator it says: VALID JSON
But I still get an invalid JSON warning by ajax.
On locations.php I have this code:
HTML
<table id="displayTable" class="table table-striped table-bordered display compact" style="width:100%">
<thead>
<tr>
<th> </th>
<th>Name</th>
<th>Address</th>
<th>Telephone</th>
</tr>
</thead>
<tfoot>
<tr>
<th> </th>
<th>Name</th>
<th>Address</th>
<th>Telephone</th>
</tr>
</tfoot>
</table>
And this JQUERY
function format ( d ) {
// `d` is the original data object for the row
return 'So Far .... NOT so Good';
}
$('#SR_sendForm').click(function(){
$('#displayTable').DataTable(
{
"order": [[ 1, "asc" ]],
"scrollY": $(window).height()-($(window).height()/10),
"scrollX": true,
"ajax": 'pages/get_SR_Locations.php?fdr='+$('#FDR').val()+'&s_term='+$('#searchterm').val()+'&city='+$('#city').val()+'&searchgroup='+$('#searchgroup').val(),
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "address" },
{ "data": "telephone" }
]
}
);
$('#responseTable').show();
}
});
// Add event listener for opening and closing details
$('#responseTable tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
And this is the error I get:
DataTables warning: table id=displayTable - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
What is wrong?
Thank you Jeff.... I did what you said ... Add json to the data instead of going via ajax.
So the solution is:
I made an tempDIV to load the data from get_SR_Locations.php
<div class="row" id="tempDIV" style="display: none"></div>
then I load the data and I use the callback for errors etc.
$('#tempDIV').load('pages/get_SR_Locations.php?fdr='+$('#FDR').val()+'&s_term='+$('#searchterm').val()+'&city='+$('#city').val()+'&searchgroup='+$('#searchgroup').val(), function(responseTxt, statusTxt, xhr) {
if(statusTxt == "success"){
$('#displayTable').DataTable(
{
"order": [[ 1, "asc" ]],
"scrollY": $(window).height()-($(window).height()/10),
"scrollX": true,
"data": JSON.parse($.trim($('#tempDIV').text())),
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "address" },
{ "data": "telephone" }
]
}
);
$('#responseTable').show();
}
if(statusTxt == "error"){
$('#responseTable').html("<b>Oops</b><br>Houston we have a problem");
alert("Error: " + xhr.status + ": " + xhr.statusText);
$('#responseTable').show();
}
});
And a last modification in get_SR_Locations.php:
I removed this line:
$mj=array("data"=>$myjson);
$myjson = array();
foreach ($locationList as $list) :
$json= array(
"id" => addslashes($list['id']),
"name" => addslashes($list['name']),
"address" => addslashes($list['address']),
"telephone" => addslashes($list['telephone']),
"emailaddress" => addslashes($list['email'])
);
array_push($myjson, $json);
endforeach;
echo json_encode($myjson);
Related
I know this must be one of the most popular questions. I can't see what's wrong with my data though. This is my php:
$sql = "SELECT eventid, event_type, date_display, date_from, date_to, location, done FROM events LIMIT 0, 30";
$get_result = mysql_query($sql);
$arr = Array();
while($res=mysql_fetch_assoc($get_result))
{
$arr['data'][] = $res;
}
echo json_encode($arr);
My JQuery:
function do_search()
{
var search_term=$("#search_term").val();
$.ajax
({
type:'post',
url:'get_results.php',
data:{
search:"search",
search_term:search_term
},
success:function(response)
{
console.log(JSON.parse(response))
$('#events').DataTable({
ajax: JSON.parse(response),
columns: [
{ data: 'eventid' },
{ data: 'event_type' },
{ data: 'date_display' },
{ data: 'date_from' },
{ data: 'date_to' },
{ data: 'location' },
{ data: 'done' },
],
"lengthMenu": [ [-1, 10, 25, 50, 100], ["All", 10, 25, 50, 100] ]
});
}
});
And my HTML:
<table id="events" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Type</th>
<th>Date</th>
<th>From</th>
<th>To</th>
<th>Location</th>
<th>To do</th>
</tr>
</thead>
</table>
This is the data I get in the console:
{
"data": [
{
"eventid": "1",
"event_type": "Senate meeting",
"date_display": "61-60",
"date_from": "61",
"date_to": "60",
"location": "Unknown",
"done": "y"
},
{
"eventid": "2",
"event_type": "Legal hearing",
"date_display": "73-70",
"date_from": "73",
"date_to": "70",
"location": "Unknown",
"done": ""
},
[etc...]
]
}
As far as I can see I'm following the data expected by DataTables. What am I missing?
I am getting seven fields for each record, and the table has seven fields indeed, also mapped in the JQuery code.
In the example at the link you posted here: https://datatables.net/examples/ajax/objects.html, the ajax option in the datatables config is used to provide the URL of the file/script which returns the JSON data, so that datatables can initiate an AJAX request to fetch it.
Whereas what you've done is make your own AJAX request, and then pass the response to datatables. If you're going to do that, you should provide it to datatables via the data option instead. Your scenario, as coded now, is actually closer to this example: https://datatables.net/examples/data_sources/js_array.html
e.g.
$('#events').DataTable({
data: JSON.parse(response),
P.S. For a more complete discussion how to configure DataTables to use an AJAX request as a data source directly, see https://datatables.net/manual/ajax
I use laravel 8 + lumen rest api server and little bit confused because when i consume timestamp and parse it to localize format date on laravel side, also separated the display and timestamp for the js side datatables, the editColumn()it make the filtered search doesn't work because the main of search params is from the timestamp i was set before but on the view i saw it use display side, so how i can make the both filtered(search) and sort work ?
response data :
array:4 [▼
0 => array:6 [▼
"id_role" => 1
"nama_role" => "super.admin"
"created_at" => "2021-11-02T07:32:00.000000Z"
"updated_at" => "2021-11-02T07:32:00.000000Z"
"created_by" => "self"
"updated_by" => "self"
]
.. => ...
]
the column i was sorted was created_at and updated at.
RoleController.php
<?php
public function index(Request $request)
{
$raw = Http::withHeaders(['Authorization' => 'Bearer ' . Cookie::get('access_token')])->get(env('API_URL') . '/v1/kelola-role/role');
$data = $raw->json('data');
$status = $raw->json('status');
if ($request->ajax()) {
if ($status == 'success') {
return DataTables::of($data)
->addIndexColumn()
->editColumn('created_at', function ($e) {
return [
'display' => Carbon::parse($e['created_at'])->format('d/m/Y'),
'timestamp' => Carbon::parse($e['created_at'])
];
})
->editColumn('updated_at', function ($e) {
return [
'display' => Carbon::parse($e['updated_at'])->format('d/m/Y'),
'timestamp' => Carbon::parse($e['updated_at'])
];
})
->make(true);
}
return abort(401);
}
return view('pages.pengaturan.kelola-role');
}
the view :
<table class="table" id="dataRole" style="width:100%">
<thead>
<tr>
<th>No</th>
<th>Nama Role</th>
<th>Dibuat Pada</th>
<th>Diupdate Pada</th>
</tr>
</thead>
<tfoot>
<tr>
<th>No</th>
<th>Nama Role</th>
<th>Dibuat Pada</th>
<th>Diupdate Pada</th>
</tr>
</tfoot>
</table>
the js side :
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
document.addEventListener("DOMContentLoaded", function() {
$("#dataRole").DataTable({
processing: true,
serverSide: true,
ajax: {
type: "GET",
url: "",
dataSrc: function(json) {
barDone();
return json.data;
}
},
columns: [{
data: 'DT_RowIndex',
name: 'DT_RowIndex',
orderable: false,
searchable: false
},
{
data: 'nama_role',
name: 'nama_role'
},
{
name: 'created_at.timestamp',
data: {
_: 'created_at.display',
sort: 'created_at.timestamp'
}
},
{
name: 'updated_at.timestamp',
data: {
_: 'updated_at.display',
sort: 'updated_at.timestamp'
}
},
],
responsive: true,
fixedHeader: true,
select: {
style: "multi"
},
language: {
url: '{{ env('APP_URL') }}/id.json',
processing: "<div id='loadercontainer'><div class='d-flex justify-content-center text-secondary' id='loader'><div class='spinner-border' role='status'><span class='sr-only'>Loading...</span></div></div></div>"
},
dom: '<"row"<"col-12 col-sm-6 py-0"l><"col-12 col-sm-6 py-0 pt-2 pt-sm-0"fr><"col-12"t><"col-12 d-flex justify-content-between"ip>>',
render: function(data, type, row, meta) {
return meta.row + meta.settings._iDisplayStart + 1;
},
});
});
created_at sort view just work
but when i search it doesn't work
You also need to transform the search on the query level. Try using filterColumn to modify how the package will search on the edited column.
In some cases, we need to implement a custom search for a specific column. To achieve this, you can use filterColumn api.
I am stuck in that I want to reset or restart the column number from 1 after executing search in Laravel using ajax in datatable.
The code i have written so far
<table class="table table-bordered table-striped table-condensed flip-content" id="server-side-datatables">
<thead>
<tr>
<th class="dt-body-left">Serial No.</th>
<th>Document Type</th>
<th>Document Nr.</th>
<th>Date</th>
<th>Amount</th>
<th>CURENCY</th>
<th>Merchnat</th>
<th>Commnets</th>
<th width="10%">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function(){
$("#search-frm").submit(function(){
oTableCustom.draw();
return false;
});
// $("#search-frm").submit(function(e) {
// table.fnPageChange(0);
// table.fnReloadAjax();
// return false;
// });
$.fn.dataTableExt.sErrMode = 'throw';
var cur_month = '{{date("M")}}';
var title = 'WEBPAL WEB SERVICES BORDEROU CONTABILITATE LUNA:'+ cur_month;
var filename = 'WEBPAL WEB SERVICES BORDEROU CONTABILITATE LUNA:'+ cur_month;
var oTableCustom = $('#server-side-datatables').DataTable({
processing: true,
dom: 'Bfrtip',
serverSide: true,
searching: false,
ajax: {
"url": "{!! route($moduleRouteText.'.data') !!}",
"data": function ( data )
{
data.search_start_date = $("#search-frm input[name='search_start_date']").val();
data.search_end_date = $("#search-frm input[name='search_end_date']").val();
data.doc_number = $("#search-frm input[name='doc_number']").val();
data.search_parteners = $("#search-frm input[name='search_parteners']").val();
}
},
"order": [[ 0, "asc" ]],
// "fnRowCallback" : function(nRow, aData, iDisplayIndex){
// $("td:first", nRow).html(iDisplayIndex +1);
// return nRow;
// },
columns: [
{ data: 'rownum', name: 'rownum' },
{ data: 'doc_type', name: 'doc_type' },
{ data: 'doc_number', name: 'doc_number' },
{ data: 'doc_date', name: 'doc_date'},
{ data: 'amount', name: 'amount' },
{ data: 'currency', name: 'currency' },
{ data: 'partener', name: '{{ TBL_PARTENER }}.id'},
{ data: 'comments', name: 'comments' },
{ data: 'action', orderable: false, searchable: false}
],
lengthMenu: [
[ 10, 25, 50, -1 ],
[ '10 rows', '25 rows', '50 rows', 'Show all' ]
],
columnDefs: [
{ "type": "num-fmt", "targets": 4, "className": "text-left", appliesTo: 'pdf' }
],
buttons: [
{
extend: 'pageLength'
},
{
extend: 'pdfHtml5',
orientation: 'landscape',
title: title,
filename:filename,
exportOptions: {
columns: [ 0, 1, 2,3,4,5,6,7 ],
},
customize : function(doc){
doc.content[1].table.widths =
Array(doc.content[1].table.body[0].length + 1).join('*').split('');
doc.styles.tableHeader.alignment = 'left';
},
},
]
});
});
</script>
#endsection
I want output like this
just use CSS code
tbody {
counter-reset: row;
/* Set the row counter to 0 */
}
tbody tr::before {
counter-increment: row;
/* Increment the row counter*/
content: counter(row) ": ";
/* Display the row */
}
I am implementing datatable in my project using instruction from https://datatables.net/examples/data_sources/server_side.html
Now I have implemented same jquery code like :
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
} );
} );
but its not working in my project and gives the error of :
DataTables warning: ********** Requested unknown parameter '0' for row 0. For more information about this error, please see http://datatables.net/tn/4
but when I specify columns in jquery like :
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php",
"columns": [
{ "data": "id"},
{ "data": "item" },
{ "data": "name" }
],
} );
} );
then it works perfectly, So whats the issue here, why I can not use it without specifying columns ?
Ajax Response :
{
"draw": 1,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
[
1,
"item1",
"name1"
],
[
2,
"item2",
"name2"
]
]
}
As far as I can see, you are accessing an array of objects instead of a two dimensional array.
Datatables default behavior is accepting data in this format:
[
[ "row 1, cell 1", "row 1, cell 2", "row 1, cell 3" ],
[ "row 2, cell 2", "row 2, cell 2", "row 2, cell 3" ]
]
If you use a different data source format, as I believe you do, you must specify the columns so datatables can map them.
You can find more information here
If possible, provide your json response to check if this is the case.
Ok, I can see your response now, and it works if you wrap your ids in double quotes.
Try this - create a file named response.php with this content:
{
"draw": 1,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
[
"1",
"item1",
"name1"
],
[
"2",
"item2",
"name2"
]
]
}
Create another file named test.php with this content:
<head>
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
</head>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Item</th>
<th>Name</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Item</th>
<th>Name</th>
</tr>
</tfoot>
</table>
<script>
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "./response.php"
} );
} );
</script>
</body>
Upload both files to your server and test it - it works.
I'm using Ignited Datatables to display posts in tabular way in my view. I've been struggling the last 4 days in order to do this working correct, but I can't understand what I'm doing wrong.
This is the functionality that fetches the data
// the Post_model
/**
* Get page data on datatables
*/
public function get_datatable() {
$this->load->library('datatables');
$this->datatables->select('id, title, slug, sort_description, status');
$this->datatables->from('posts');
return $this->datatables->generate();
}
// the posts controller
/**
* List all posts
*/
public function index() {
$this->data['datatables'] = true;
$this->data['data_url'] = 'admin/posts/data_ajax';
// $this->data['posts'] = $this->post_model->get_datatable();
// dump($this->data['pages']);
// load view
$this->load->view('admin/posts/index', $this->data);
}
public function data_ajax() {
$this->output->enable_profiler(false);
echo $this->post_model->get_datatable();
// echo json_encode($this->post_model->get_datatable());
exit();
}
// the view
<table class="table dataTable table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Url Slug</th>
<th>Sort Description</th>
<th>Status</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Title</th>
<th>Url Slug</th>
<th>Sort Description</th>
<th>Status</th>
</tr>
</tfoot>
<!-- <tbody>
<tr>
<td colspan="5" class="dataTables_empty"></td>
</tr>
</tbody> -->
</table>
<?php if(isset($datatables)): ?>
<?php echo js_tag('js/dataTables/jquery.dataTables.min.js'); ?>
<?php echo js_tag('js/dataTables/dataTables.bootstrap.min.js'); ?>
<script type="text/javascript">
$(document).ready(function() {
$('.dataTable').DataTable({
'bProcessing' : true,
'bServerSide' : true,
'sAjaxSource' : '<?php echo base_url($data_url); ?>',
'sServerMethod' : 'POST',
'fnServerData' : function (sSource, aoData, fnCallback) {
$.ajax({
dataType : 'json',
type : 'post',
url : sSource,
data : aoData,
success : fnCallback,
"columns": [
{ "data": "id" },
{ "data": "title" },
{ "data": "slug" },
{ "data": "sort_description" },
{ "data": "status" }
]
});
}
});
});
</script>
<?php endif; ?>
So if I access the data_ajax() function from the url like this
localhost/my-blog/admin/posts/data_ajax
and echo echo $this->page->get_datatable(); I can the records
{"draw":0,"recordsTotal":2,"recordsFiltered":2,"data":[{"id":"1","title":"First post","slug":"first-post","sort_description":"This is the first post","status":"visible"},{"id":"2","title":"Second post","slug":"second-post","sort_description":"This is the second post","status":"visible"}]}
but the problem is I can't display them on my screen. In addition I also get this warning in an alert box
DataTables warning: table id=DataTables_Table_0 - Requested unknown parameter '0' for row 0. For more information about this error, please see http://datatables.net/tn/4
This is a screenshot of what I get
How can I make this work properly? Any help would be appreciated
Please try this
Add Columns parameter to associate data with column
The code will be something like this
$('.dataTable').DataTable({
'bProcessing' : true,
'bServerSide' : true,
'sAjaxSource' : '<?php echo base_url($data_url); ?>',
'sServerMethod' : 'POST',
"columns": [
{ "data": "id" },
{ "data": "title" },
{ "data": "slug" },
{ "data": "date_published" },
{ "data": "status" }
]
'fnServerData' : function (sSource, aoData, fnCallback) {
$.ajax({
dataType : 'json',
type : 'post',
url : sSource,
data : aoData,
success : fnCallback,
});
}
});
Please refer datatables column, for details
I had similar problem. This is how I got it solved:
You have to set the columns as this
"columns": [null, null, null, null, null,{}]
Set it separately not in the Ajax.