Datatables Ajax call not displaying data - ajax

I'm using the datatables library to display some data and would like to update this every 30 seconds with data fetched form a URL. I've followed the api documentation and have implemented the code below to do this:
$( document ).ready(function() {
var table = $('#performance_summary').DataTable( {
ajax: 'https://myjasonurl.com'
} );
setInterval( function () {
table.ajax.reload();
}, 30000 );
});
When the page loads I can see that the correct URL is called to retrieve data, and data is returned in the correct format to display properly in the table (I've checked this works by loading this into the table directly). Unfortunately the resulting datatable when using the ajax call states that it is "loading" but never loads/shows the data, does anyone have any idea of how I fix this?

Try the DataTable().ajax.url function,
Following code works fine for me:
$(document).ready(function() {
var table = $('#performance_summary').DataTable({
paging: false,
searching: false,
ajax: "https://api.myjson.com/bins/897v1",
columns: [{
"title":"Test",
"data": "test"
}]
});
setInterval( function () {
$('#performance_summary').DataTable().ajax.url(
"https://api.myjson.com/bins/897v1"
).load();
}, 3000 );
});
here's the fiddle: https://jsfiddle.net/ju2bmtm7/84/

Related

Redraw datatables with search

I am using DataTables. I have added the below code when the page is loading and the table getting all data as expected.
var table = $('#expensesTable').DataTable({
responsive: true,
searchDelay: 500,
processing: true,
serverSide: true,
ajax: {
url: '/books/daybooks/datatable',
type: 'POST',
},
columns: [
{data: 'expense_id'},
{data: 'expense_date'},
{data: 'expense_description'},
{data: 'expense_amount'},
{data: 'vendor_name'},
],
});
Now, I have added a date range picker where it will search data in the server and response will be given back to query via Ajax.
$('#datepicker').on('apply.daterangepicker', function(ev, picker) {
var start = picker.startDate.format('YYYY-MM-DD');
var end = picker.endDate.format('YYYY-MM-DD');
jQuery.ajax({
type: "POST",
url: '/books/daybooks/datatable',
data: {start : start, end : end},
success: function(data)
{
console.log(data);
} // Success End
}); //AJAX End
});
Now i am getting all expected filter data as success, but now I need to redraw the table with newly got data after the filter of Ajax call.
if i use $('#expensesTable').DataTable().draw(); then it will do draw without filter,
So i can draw table with filter data?
Thanks in advance.
Instead of introducing a new ajax call (the jQuery ajax), you can re-use your existing DataTables ajax call when submitting your date range filter data.
To do this, you need to take the following steps:
(1) Update your DataTables ajax option:
ajax: {
url: '/books/daybooks/datatable',
type: 'POST',
data: function () {
return { "start": start, "end" end };
}
},
This data function allows you to dynamically assign values to your request. They will be added as standard URL-encoded form data, in the usual way for POST requests.
See here for more information. There are several different ways to use ajax.data. For example, if you were using serverSide processing (which you are not) then the above approach would not work correctly.
(2) To re-use your DataTables ajax call, you can use this:
table.ajax.reload();
See here for more information.
This replaces your jQuery ajax call:
var start;
var end;
$('#datepicker').on('apply.daterangepicker', function(ev, picker) {
start = picker.startDate.format('YYYY-MM-DD');
end = picker.endDate.format('YYYY-MM-DD');
table.ajax.reload();
});
When the table first loads (not using reload()), the filter values will be null.

How to get number of rows in datatable after ajax load

"ajax": {
"url": "<%=request.getContextPath()%>/Home?value=getreqs5",
"data": function ( json,callback) {
var oTable = $('#fifth').dataTable();
// Get the length
var count=oTable.fnGetData().length;
return json;
}
}
Ajax data is successfully loaded in datatable.But the number of rows showing zero. How can i get number of rows in datatable after ajax return data?
If you are using datatables 1.10 you can get the total rows number with
"ajax": {
"url" : "<%=request.getContextPath()%>/Home?value=getreqs5",
"dataSrc": function(res){
var count = res.data.length;
alert(count);
return res.data;
}
}
With the dataSrc you can get the ajax success callback. In this callback you can count the objects number than your Ajax returns.
If you want to know how many rows you have in all your Datatable including all rows in all pages you can do this in your datatables parameter but out your ajax parameter :
"initComplete": function(settings, json){
var info = this.api().page.info();
alert('Total records', info.recordsTotal);
}
Just adding for all people looking for how to get to the api in other usecases:
var table = $("#myTable").dataTable();
table.on('draw', function (data) {
console.log(table.page.info().recordsDisplay);
});

For how many rows AJAX data loading in data tables makes sense

I am using a table with data tables plugin (https://datatables.net). I don't want to load data via AJAX because this causes trouble when using the download extension (will only download the loaded rows).
But I know that if my table is too big browser can get very slow when loading all rows at once.
So my question is: up to how many rows can I load at once in my HTML and when does it make sense to use ajax.
I know it depends on many factors...my table has around 7 columns. I don't need an exact number of course but are we talking about dozens, hundreds or thousands?
Thanks!
It's hard to say about number of records, I believe up to 5000 should be acceptable. Depending on particular scenario.
There is FAQ about speed https://datatables.net/faqs/#speed
There is a way of viewing one set of data and saving another set.
https://datatables.net/extensions/buttons/examples/html5/customFile.html
$(document).ready(function() {
$('#example').DataTable( {
serverSide: true,
ajax: // request to get a page of data,
// ....
dom: 'Bfrtip',
buttons: [
{
text: 'JSON',
action: function ( e, dt, button, config ) {
var data = dt.buttons.exportData();
$.ajax({
url: 'your_server_data_file.json',
success: function(data) {
$.fn.dataTable.fileSave(
new Blob( [ JSON.stringify( data ) ] ),
'Export.json'
);
});
}
}
]
} );
} );
And just in case https://datatables.net/manual/server-side

Use ajax to filtering data table in codeigniter

i'm using codeigniter to build my project. I want to make filter use select box with ajax, but i confused. when user choose values from select box, then i want the table just show data that contain select box values. Can anyone help me please...
<script>
function show_result()
{
if($('#selectbox').val()!='')
{
$.ajax({
type: "POST",
url:'<?php echo base_url()?>controller/controller_function',
data:'selectvalue='+$('#selectbox').val(),
cache: false,
beforeSend : function ()
{
$("#idAjaxLoader").css("display",'');
},
success: function (data) {
$("#idAjaxLoader").css("display",'none');
$('#table-div').html(data);
},
error: function(data){
//return false;
}
});
}
}
</script>
write query in controller's controller_function and then load view with table by your expected result

Updating a dropdown via knockout and ajax

I am trying to update a dropdown using knockout and data retrieved via an ajax call. The ajax call is triggered by clicking on a refresh link.
The dropdown is successfully populated when the page is first rendered. However, clicking refresh results in clearing the dropdown instead of repopulating with new data.
Html:
<select data-bind="options: pages, optionsText: 'Name', optionsCaption: 'Select a page...'"></select>
<a id="refreshpage">Refresh</a>
Script:
var initialData = "[{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}]";
var viewModel = {
pages : ko.mapping.fromJS(initialData)
};
ko.applyBindings(viewModel);
$('#refreshpage').click(function() {
$.ajax({
url: "#Url.Action("GetPageList", "FbWizard")",
type: "GET",
dataType: "json",
contentType: "application/json charset=utf-8",
processData: false,
success: function(data) {
if (data.Success) {
ko.mapping.updateFromJS(data.Data);
} else {
displayErrors(form, data.Errors);
}
}
});
});
Data from ajax call:
{
"Success": true,
"Data": "[{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}]"
}
What am I doing wrong?
The problem you have is that you are not telling the mapping plugin what to target. How is it suppose to know that the data you are passing is supposed to be mapped to the pages collection.
Here is a simplified version of your code that tells the mapping what target.
BTW The initialData and ajax result were the same so you wouldn't have noticed a change if it had worked.
http://jsfiddle.net/madcapnmckay/gkLgZ/
var initialData = [{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}];
var json = [{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"}];
var viewModel = function() {
var self = this;
this.pages = ko.mapping.fromJS(initialData);
this.refresh = function () {
ko.mapping.fromJS(json, self.pages);
};
};
ko.applyBindings(new viewModel());
I removed the jquery click binding. Is there any reason you need to use a jquery click bind instead of a Knockout binding? It's not recommended to mix the two if possible, it dilutes the separation of concerns that KO is so good at enforcing.
Hope this helps.

Resources