JS Datatable not displaying AJAX response - javascript

Datatable is not displaying the response of an AJAX call to flask backend.
The data is retrieved as I can see it in the console.log of the success field of the AJAX call, however its not populating in the table.
Here is the JSON:
{'events':
[
{
'TIME': 'Evening',
'DESCRIPTION': 'test1'
},
{
'TIME': 'Morning',
'DESCRIPTION': 'test2'
}
]
}
This is the JS part:
function load_table() {
var payload = {'from_date': $('#from_date').val(), 'to_date': $('#to_date').val()}
$('#table').DataTable({
pageLength: 50,
paging: true,
ajax: {
url: "data/get-events/" + JSON.stringify(payload),
dataType: "json",
type: 'GET',
error: function(e){
alert(e);
},
success: function(e){
console.log(e);
},
dataSrc: 'events'
},
columns: [
{ title: 'Time', data: 'TIME'},
{ title: 'Event', data: 'DESCRIPTION'}
],
bDestroy: true,
});
}
I tried the tens of answers to my similar question but none of them worked.

Related

Datatable AJAX Data Parameter is not refreshing

I'm stuck on a portion of my datatable Ajax reload. In the beginning of my javascript file I have the following:
var courtDateSelected;
docketCheckedInDataTable = $('#data-checked-in').DataTable({
ajax: {
type: "POST",
url: base_url + '/courts/dockets/api/list1',
dataType: 'json',
data: {
'court_date_id': courtDateSelected,
'checked_in': 'true',
},
error: function (xhr, error, code)
{
console.log(xhr);
console.log(code);
},
"dataSrc": function (json) {
//Make your callback here.
$('#checkedInCount').html(json.data.length);
return json.data;
}
},
"paging": true,
"dom": '<"datatable-header"f>rt<"datatable-footer"p>',
"ordering": true,
"bLengthChange": false,
"autoWidth": false,
"searching": true,
"info": false,
"order": [],
"columns": [
{data: 'view', name: 'view', orderable: false},
{data: 'docket_number', name: 'docket_number', orderable: false},
{data: 'last_name', name: 'last_name', orderable: true},
{data: 'first_name', name: 'first_name', orderable: false},
{data: 'balance', name: 'balance', orderable: false},
{data: 'actions', name: 'actions', orderable: false},
],
language: {
search: "_INPUT_",
searchPlaceholder: "Search Keywords...",
emptyTable: "There are no available dockets for the selected court session."
}
});
I have a date selector where it sets the variable's (courtDateSelected) value to the value selected and then sets off this script:
function reloadCheckinPageTables(){
console.log('begin');
console.log(courtDateSelcted);
console.log('end');
docketCheckedInDataTable.ajax.reload();
docketDataTable.ajax.reload();
docketPendingCheckoutDataTable.ajax.reload();
}
The problem is that my console log's the following:
begin
894
end
Which leads me to believe that the variable has been successfully updated, however, this variable's update value is not passed onto the data parameters in the DataTable.
For dynamically calculated data, you should use ajax.data as a function. Something like:
ajax: {
...
data: fundtion(d) {
d.court_date_id = courtDateSelected;
d.checked_in = 'true';
}
...

Reload datatable after dropdown value changed

I have a datatable and a dropdown. I want to change the datatable after dropdown value change. First of all, I tried the simplest trial & error by getting return value from controller after dropdown changes value and it works smoothly. Here is my code:
$('#ID_Univ').change(function () {
$.ajax({
type: 'GET',
url: '#Url.Action("Get_Approved")',
data: { ID: _Id },
success: function (data) {
// data, I got return value
// do something here
}
});
});
and then here is my datatable code
var tbl_Approved = $('#tbl_Approved').DataTable({
lengthMenu: [10, 25, 50, 75, 100],
searchPane: {
columns: [':contains("Name")', ':contains("Period")'],
threshold: 0
},
////////////////////////////////////
processing: true,
serverSide: true,
ajax: { ??? },
////////////////////////////////////
columns: [
{ data: 'ID_Approved_Monthly', title: "ID" },
{ data: 'Name', title: "Name" },
{ data: 'Period', title: "Period" },
{ data: 'Approved', title: "Approved" },
{ data: 'Approved_Date', title: "Approval Date" },
{ data: 'Paid_Status', title: "Paid Date" },
],
columnDefs: [{
targets: [0],
visible: false,
searchable: false
}],
dom: 'Rlfrtip'
});
I put datatable code outside $(document).ready(function (). So, when the page reload, it just reload the datatable as variable and whenever dropdown's value changed it just call datatableName.ajax.reload();. That's the idea.
Now, my question are,
how do I put the ajax call in the datatable to reload datatable that det return value from controller (ASP .Net Core). I see someone did this flawlessly in youtube but it made by PHP. I have same idea with this youtube.
why I don't see any change in my datatable when dropdown value change ? even, I've put ajax.data according to "Add data to the request (returning an object)"
in this case, do I have to use server side ?
So here is my complete code, what I've been trying till right now and still get stuck.
<script type="text/javascript">
var tbl_Approved = $('#tbl_Approved').DataTable({
lengthMenu: [10, 25, 50, 75, 100],
searchPane: {
columns: [':contains("Name")', ':contains("Period")'],
threshold: 0
},
////////////////////////////////////
processing: true,
serverSide: true,
ajax: { //I get get stuck here :((
"datatype": "json",
type: 'GET',
url: '#Url.Action("Get_Approved")',
data: function (d) {
return $.extend({}, d, {
ID: $('#ID').val(),
})
}
},
////////////////////////////////////
columns: [
{ data: 'ID_Approved_Monthly', title: "ID" },
{ data: 'Name', title: "Acc Name" },
{ data: 'Period', title: "Period" },
{ data: 'Approved', title: "Approved" },
{ data: 'Approved_Date', title: "Approval Date" },
{ data: 'Paid_Status', title: "Paid Date" },
],
columnDefs: [{
targets: [0],
visible: false,
searchable: false
}],
dom: 'Rlfrtip'
});
$(document).ready(function () {
tbl_Approved_Allowance.draw();
$('#ID').change(function () {
tbl_Approved_Allowance.ajax.reload();
}
});
})
</script>
to solve this problem, I put ajax into .change(function()). Here is my code:
$('#ID').change(function () {
$.ajax({
type: 'GET',
url: '#Url.Action("Get_Approved")',
data: { ID: ID},
success: function (data) {
$('#tbl_Approved').DataTable({
destroy: true,
data: data,
lengthMenu: [10, 25, 50, 75, 100],
searchPane: {
columns: [':contains("Name")', ':contains("Period")'],
threshold: 0
},
columns: [[
{ data: 'ID_Approved_Monthly', title: "ID" },
{ data: 'Name', title: "Acc Name" },
{ data: 'Period', title: "Period" },
{ data: 'Approved', title: "Approved" },
{ data: 'Approved_Date', title: "Approval Date" },
{ data: 'Paid_Status', title: "Paid Date" },
],
dom: 'Rlfrtip'
});
}
})
});

How to send Select2 AJAX POST with body?

I am using select2 with ajax. The data needs to be fetched using a POST request with some payload in the body.
POST request is being sent but the data is urlencoded and sent as request payload instead of request body.
I am trying this:
self.$("#elem-id").select2({
placeholder: 'Placeholder Text',
allowClear: true,
ajax: {
type: 'POST',
url: 'my_url',
dataType: 'json',
data: function(term, page) {
return {
q: term,
q2: [{
"hello": "world"
}]
};
},
params: {
headers: getHeaders(),
contentType: "application/json"
},
quietMillis: 250,
results: function(data, page) {
return {
.....
};
},
cache: true
}
});
Pass the object you return in the done function through JSON.stringify function
data: function(term, page) {
return JSON.stringify({
q: term,
q2: [{
"hello": "world"
}]
});
},

Laravel datatable invalid JSON response

Everything work fine on code below to fetch user logs:
js:
<script>
$(document).ready(function () {
var table =$('#systemLogs').DataTable({
responsive: true,
processing: true,
serverSide: true,
"language": {
"url": "/datatables/media/plug-in/Persian.json"
},
ajax: '{!! url('/admin/systemLogs/data/systemLogsDataTable') !!}',
columns: [
{ data: 'name', name: 'name' },
{ data: 'message_text', name: 'message_text' },
{ data: 'remote_addr', name: 'remote_addr' },
{ data: 'log_created_at', name: 'management_logs.created_at' },
{ data: 'log_updated_at', name: 'management_logs.updated_at' },
]
});
});
</script>
routes:
Route::get('/systemLogs/data/systemLogsDataTable','SystemLogsController#systemLogsDataTable');
public function systemLogsDataTable()
{
$logs= ManagementLog::select('management_logs.message_text','management_logs.remote_addr','management_logs.created_at as log_created_at','management_logs.updated_at as log_updated_at','managements.name')->leftJoin('managements','management_logs.management_id','=','managements.id');
return Datatables::of($logs)->make(true);
}
It works fine for me but when I want to fetch just 2 fields from database it will give me
DataTables warning:table id=systemLogs - invalid JSON response.
but some times it will work ok.
<script>
$(document).ready(function () {
var table =$('#systemLogs').DataTable({
responsive: true,
processing: true,
serverSide: true,
"language": {
"url": "/datatables/media/plug-in/Persian.json"
},
ajax: '{!! url('/admin/systemLogs/data/systemLogsDataTable') !!}',
columns: [
{ data: 'name', name: 'name' },
{ data: 'message_text', name: 'message_text' },
]
});
});
</script>
I have understood which the problem is from middleware:
public function handle($request, Closure $next,$guard = 'admin')
{
if(!Auth::guard($guard)->check()){
return redirect('/administrator/logout');
}else{
return $next($request);
}
}
when I changed it to:
public function handle($request, Closure $next,$guard = 'admin')
{
return $next($request);
}
It works fine so it means the problem is from AJAX.
what do I have to do?
It's because if you're not logged into application the response is gonna be a redirect and this is a invalid AJAX response, you can try this to handle redirect response:
$(document).ready(function () {
var table =$('#systemLogs').DataTable({
responsive: true,
processing: true,
serverSide: true,
"language": {
"url": "/datatables/media/plug-in/Persian.json"
},
ajax: function(data, callback, settings) {
// make a regular ajax request
$.get('{!! url('/admin/systemLogs/data/systemLogsDataTable') !!}', function(res) {
if(res.redirect)
window.location.href = res.redirect;
callback({
data: JSON.parse(res)
});
});
},
columns: [
{ data: 'name', name: 'name' },
{ data: 'message_text', name: 'message_text' },
{ data: 'remote_addr', name: 'remote_addr' },
{ data: 'log_created_at', name: 'management_logs.created_at' },
{ data: 'log_updated_at', name: 'management_logs.updated_at' },
]
});
});
First, are you using php artisan serve? I think yes, so I suggest you use homestead/valet or any apache/nginx stack.
It's been a known weird bug of the package where Laravel randomly returns redirect/404 response when using artisan serve.
-- Edit --
Updated the package documentation and advise the known bug.
https://github.com/yajra/laravel-datatables#php-artisan-serve-bug

How to send Jquery datatable data to servlet?

I want to send Jquery datatable to servlet. below is the code.
Jquery in JSP
var table2 = $('#itemtable').DataTable( {
columns: [
{ data: "p_no"},
{ data: "p_date"},
{ data: "s_id"},
{ data: "it_id" },
{ data: "it_name" },
{ data: "it_type" },
{ data: "it_uni_price" },
{ data: "it_qty" },
{ data: "it_tot_price" }
],
order: [ 1, 'asc' ],
bProcessing: true,
bSort: true,
bJQueryUI: true,
bLengthChange: true,
bPaginationType: "two_button"
} );
Ajax request on Save button as below
var oTable = $("#table2").dataTable();
updateDatabase(oTable.fnGetData());
And the updateDatabase() as below
function updateDatabase(dataTable) {
$.ajax({
type: "POST",
url: "/ERP/Purchase",
cache: false,
dataType: "json",
data:{dataTable: dataTable},
success: function(html){
//success
}
});
}
How do I get my datatable data to my servlet?

Categories

Resources