I am getting a weird error after reloading dataTable, most functions returns null. I tried table.fnDestroy and then table.datatable() but no luck.
var oTable = $('#sample_table').dataTable();
var nRow = $(this).parents('tr')[0];
var aData = oTable.fnGetData(nRow); //works
After table reload
var nRow = $(this).parents('tr')[0];
var aData = oTable.fnGetData(nRow); //returns null
Here is a test case showing the issue : JSFiddle
Any Ideas?
Thanks.
DataTables keeps track of the data internally, so it is unaware of external changes made to the table elements. Use the provided API to reload data into DataTables.
I would initialize DataTables with some options that specify how to render the Edit column using the mRender callback:
var oTable = $('#sample_editable_1').dataTable({
"aoColumnDefs": [{
"aTargets": [4],
"mRender": function (data, type, full) {
return '<a class="edit" href="javascript:;">Edit</a>';
}
}]
});
Now in your reload callback, instead of replacing the body of the table you can use fnClearTable and fnAddData:
$('body').on('click', '#reload', function () {
//this is where ajax will be added
var theData = ['New', 'New', 'New', 'New', null];
var theTable = $('#sample_editable_1').dataTable();
theTable.fnClearTable();
theTable.fnAddData(theData);
});
Related
Hi have an api made with Laravel. This api will return the paginatted records of data. So it will include the data, count, total, hasMorePages and currentPage. I am retur
How do I customize the pagination links in the DataTable? Also, I want to put a callback ajax function to fetch the next page. I checked the documentation https://datatables.net/reference/option/serverSide
But I cannot find what I need to match my requirements. Here's my javascript:
$("#search_games").click(function(){
var from = $("#from_date").val();
var to = $("#to_date").val();
console.log(from);
console.log(to);
$.post("/api/v1/get_games_result", { from: from, to: to }, function (data) {
if ( ! $.fn.DataTable.isDataTable( '#example' ) ) {
var t = $('#example').DataTable();
t.clear().draw();
var count = data.count;
var currentPage = data.currentPage;
var hasMorePages = data.hasMorePages;
var total = data.total;
var records = data.data;
console.log(records.length);
$.each(records, function (key, value) {
var game_data = value.game_data;
t.row.add( [
game_data.game_id,
game_data.game_date+" "+game_data.game_time,
game_data.game_closing
] ).draw( false );
});
}
var info = t.page.info();
console.log(data);
});
});
I want to make a function that when user clicked the pagination page button, I will request for the next page:
I think that you get the ID of Next link.
Then add the click event in the IF clause:
if ( ! $.fn.DataTable.isDataTable( '#example' ) ) {
<....>
$('#ID of Next link').click(function() {
Repost JSON Code here;
});
}
** HI friends .I try to bind the data in table using jquery.But is not working and the value is not showing .I am a beginner in jquery.
Can you modify my code. And can you say which is more good and fast to bind values asp or jquery**
<script src="Data_Table.js"></script>
<script>
$(document).ready(function (){
bind(res);
});
function bind(res) {
url = "XXXX.aspx/XXXXXX";
var rows = JSON.parse(res.d);
if (res.d != "[]") {
var data = [];
$.each(rows, function (index, row) {
data.push([++index
, row.Id
, row.date
, row.shift
, row.Door
, row.Green
, row.Time
, row.Cycle
, row.Fault
]);
});
table = $("#XXX").DataTable({
destroy: true,
data: data,
deferRender: true,
paging: true,
});
} else {
alert("No Record Found");
}
}
</script>
I'm not good in JavaScript and I wish someone could help.
The issue is this:
$(function(){
$('.preview-add-button').click(function(){
var form_data = {};
form_data["concept"] = "café Noir";
form_data["status"] = parseFloat(10).toFixed(2);
form_data["description"] = 1;
form_data["amount"] = parseFloat(10 * form_data["description"]).toFixed(2);
form_data["remove-row"] = '<span class="glyphicon glyphicon-remove"></span>';
var row = $('<tr></tr>');
$.each(form_data, function( type, value ) {
$('<td class="input-'+type+'"></td>').html(value).appendTo(row);
});
$('.preview-table > tbody:last').append(row);
calc_total();
});
The JavaScript works perfectly but I need to send the table to a php so that it can be stored in database.
The complete source code is from bootsnipp.
Modify to your taste and add this to your code
$.post('your_post_url',
{
data: value,
data: value
},
function(data)
{
//what to do when ajax request completes
})
I'm using Angular Data Tables (0.5.2) with DataTables 1.10.12 to load a Data Table instance. In the UI I provide a DatePicker (start and end date) for the user to select in order to limit the data by a date range. When the user click a submit button, my plan is to send a Data Tables ajax request back to the server to perform a new query including the start and end dates.
I have the Data Tables ajax.reload() working in the code below, however, I cannot get the start and end date values added to the ajax form post. I've tried several different configurations but none have worked. Can anyone suggest a working solution to simply invoke an ajax request with custom parameters to the server so that it can reprocess the request and send back updated results to Data Tables? Thanks!
//HTML
<table datatable="" dt-instance="vm.dtInstance" dt-options="vm.dtOptions" dt-columns="vm.dtColumns" class="table table-striped table-bordered table-hover dataTable"></table>
//CONTROLLER
function dashboardDownloadsCtrl($scope, dataService, DTOptionsBuilder, DTColumnBuilder, DTInstanceFactory, DTRenderer) {
var vm = this;
vm.dtInstance = {};
vm.dtOptions = DTOptionsBuilder.newOptions()
.withDOM('<"html5buttons"B>lTfgitp')
.withOption('ajax', {
type: 'POST',
dataSrc: 'data',
url: dataService.dashboard.downloads.route
})
.withOption('fnPreDrawCallback', function () { console.log('loading..') })
.withOption('fnDrawCallback', function () { console.log('stop loading..') })
.withOption('processing', true)
.withOption('serverSide', true)
.withOption('responsive', true)
.withPaginationType('full_numbers');
vm.dtColumns = [
DTColumnBuilder.newColumn('RowNum').notVisible(),
DTColumnBuilder.newColumn('first_name').withTitle('First name'),
DTColumnBuilder.newColumn('last_name').withTitle('Last name')
];
}
// Directive submit button click
$('button.applyBtn').click(function () {
var $el = $(this);
var startDate = $('.daterangepicker_start_input input').val();
var endDate = $('.daterangepicker_end_input input').val();
//get reference to controller
var dtVm = scope.$parent.vm;
var dtInstance = dtVm.dtInstance.DataTable;
// add start and end date picker values to ajax data source and call reload
dtVm.dtOptions.ajax.data = function(d) {
d.datepicker_start_date = startDate;
d.datepicker_end_date = endDate;
};
var resetPaging = true;
dtInstance.ajax.reload(function(json){
console.log('callback');}, resetPaging);
});
I got it working by simply adding the data method initialization. Apparently, this has to be set before you update the field values in the Ajax reload callback.
.withOption('ajax', {
type: 'POST',
dataSrc: 'data',
url: dataService.dashboard.downloads.route,
data: function (d) {
d.datepicker_start_date = $('.daterangepicker_start_input input').val();
d.datepicker_end_date = $('.daterangepicker_end_input input').val();
}
})
In my project I'm using Parse.com as server and database, and DataTable plugin to create a table showing the data returned. There's no problem when I use a predefined json file, but when I try to construct a local json file using the data returned from Parse.com I get an error. It seems no matter what I do, the table creation process is run first and only afterwards the json object is created.
JSfiddle with the relevant code is here. Please note that due to the large amount of code I did not provide a working sample, but only the relevant part.
function getDataFromParse(){
console.log("test function run");
var loc_json={
"data":[]
};
//get data from parse
var parseTable = Parse.Object.extend("parseTable");
var tableObj = new parseTable();
var query = new Parse.Query(parseTable);
var count=0;
query.descending("createdAt");
query.find({
success: function(resultArr){
console.log("retreiving data from parse");
for(var i=0;i<resultArr.length;i++){
query.get(resultArr[i].id,{
success: function(tableObj){
var ret_phone = tableObj.get("phone");
var ret_first = tableObj.get("firstName");
var ret_last = tableObj.get("lastName");
var ret_status = tableObj.get("redemption_status");
var ret_vipCode = tableObj.get("vipCode");
loc_json.data.push([count,ret_first +" "+ret_last,ret_phone,tableObj.get("createdAt"),ret_vipCode]); //construction of local json
count++;
console.log("finished fetching data for "+ret_first+" "+ret_last);
},
error: function(object, error) {
console.log("could not do something "+error.message);
}
});
}
console.log("success function end");
},
error: function(error){
console.log(error.message);
}
});
console.log("trying to return json");
return loc_json;
}
var rows_selected = [];
console.log("table creation");
var table = $('#example').DataTable({
ajax: getDataFromParse(), // ajax: 'https://api.myjson.com/bins/4qr1g', THIS WORKS!!
columns: [
{},
{ data: 1},
{ data: 2 },
{ data: 3 }
],
'columnDefs': [{
'targets': 0,
'searchable':false,
'orderable':false,
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<input type="checkbox">';
}
}],
'order': [1, 'asc'],
'rowCallback': function(row, data, dataIndex){
// Get row ID
$('input.editor-active', row).prop( 'checked', data[3] == 1 )
var rowId = data[0];
// If row ID is in the list of selected row IDs
if($.inArray(rowId, rows_selected) !== -1){
$(row).find('input[type="checkbox"]').prop('checked', true);
$(row).addClass('selected');
console.log("table trying to create itself");
}
}
});
SOLUTION
Remove ajax option from DataTables initialization options.
Call getDataFromParse() after initializing the DataTable
In the success handler for each query, replace this line:
loc_json.data.push([count, ret_first + " " + ret_last, ret_phone, tableObj.get("createdAt"), ret_vipCode]);
with the line below to add a new row to the table.
$('#example').DataTable()
.row.add([
count,
ret_first + " " + ret_last,
ret_phone,
tableObj.get("createdAt"),
ret_vipCode
])
.draw(false);
DEMO
See this jsFiddle for code and demonstration.
NOTES
The drawback of this solution is that a new row would be added once each query finishes successfully. Not sure if it is possible with Parse.com to handle event when all queries are completed.
Your example uses jQuery DataTables 1.9 but you're using option names and API from 1.10. You need to upgrade your jQuery DataTables library.
You're supplying data to jQuery DataTables using ajax option were in fact you should be using data option instead.
Remove code after // FOR TESTING ONLY as it was needed for demonstration only in jQuery DataTables - Row selection using checkboxes article and is not needed for production.