datatables ajax reload from new source - javascript

How do I reload datatables with the new ajax functionality?
I think it's a problem of scope.
function load_table(tableName,src)
{
var oTable = $('#'+tableName).DataTable({
'bProcessing' : true,
'bServerSide' : true,
'responsive' : true,
'sAjaxSource' : src,
'fnServerData' : function(sSource, aoData, fnCallback)
{
$.ajax({
'dataType': 'json',
'type' : 'POST',
'url' : sSource,
'data' : aoData,
'success' : fnCallback
});
},
});
}
Try to reload it from a different data source:
$("input[type="button"]").on('click',function()
{
oTable.ajax.url( 'newsource' ).load();
alert( 'Data source: '+oTable.ajax.url() );
});
Alert outputs : src : newsource
Browser loads table from src: oldsource

I've had the same issue to anyone who runs into this problem in the future here is the solution:
To accomplish reloading of data from a different source:
refer to the DOM table element NOT the DataTable object or you will get a reinitilization error:
step 1: clear data :
$('#your_table_name').DataTable().clear();
step 2: Destroy the DataTable object
$('#your_table_name').DataTable().destroy();
if you're using child rows this is very important remove the click listener
$( "#your_table_name tbody" )
.off( "click", "td.details-control");
Reinit DataTables:
loadTable('newsource','your_table_name')
and your loadTable function
function loadTable(src,tableName)
{
var oTable = $('#'+tableName).DataTable({
'bProcessing' : true,
'bServerSide' : true,
'responsive' : true,
"sDom": '<"toolbar"lfr>tip<"F">R',
'sAjaxSource' : src,
});
//initchildrows()
}

Yes, this seems to be a scope problem. You assign the dataTables instance to a local variable :
function load_table(tableName,src)
{
var oTable = $('#'+tableName).DataTable({
'bProcessing' : true,
...
assign it to a global variable instead :
var oTable;
function load_table(tableName,src)
{
oTable = $('#'+tableName).DataTable({
'bProcessing' : true,
...
If it still not works - but it should, you are using oTable.ajax.url(<src>).load() just right - then simply reinitialise the table with the destroy : true option :
var oTable;
function load_table(tableName,src)
{
oTable = $('#'+tableName).DataTable({
destroy : true,
'bProcessing' : true,
...
and call load_table from the event :
$("input[type='button']").on('click',function()
{
load_table('tableName', 'newsource');
});

Thanks,Here is my solution,it is not perfect,must send twice url,thanks to this author: How do I modify ajax url of a query datatable? eg: if you If you initialize datatable like this:
var datatables_options = {
"aLengthMenu" : [ [ 5, 10, 50, 100,500, -1 ],[ 5, 10, 50, 100,500, "All" ] ],
"iDisplayLength" : 5,
"sDom": 'T<"clear">rt<"float_left"i><"float_right_nexpage"p><"float_right_display"l>',
<'float_right_nexpage'p> <'float_right_display'l>>",
"bSort" : false,
"bProcessing" : false,
"bServerSide" : true,
"bStateSave" : true,
"bDestroy" : true,
"bDeferRender":true,
"bJQueryUI" : false,
"sScrollX" : "100%",
"bStateSave":true,
"language" : oLanguageData,
"aoColumns" : aoColumnsData,
"fnDrawCallback" : function() {
//Checkbox status updates
$("#uniform-check-all").removeClass("checker");
$("span").removeClass("checked");
$("span #check-all").attr("checked",false);
$.uniform.update();
},
"fnRowCallback" : function(nRow, aData,
iDataIndex) {
},
"sAjaxSource" : "wageQuery.action?wageDate="
+ date,
"fnServerData" : function(sSource, aoData,
fnCallback) {
$.ajax({
"type" : 'post',
"async":false,
"url" : sSource,
"dataType" : "json",
"data" : aoData,
"success" : function(resp) {
fnCallback(resp);
}
});
},
"fixedColumns": {
"iLeftColumns" : 4,
"sHeightMatch" : "auto"
},
};
import: if you want to reload new url(action),here is the solution: first step: Initialize table variables at the JSP file,like this:
<script type="text/javascript">
var wageNowTable;//Table global variables, do not put in the ready function, otherwise it is not a global variable
</script>
second step: Add the following code to the JS file,like this:
$("#wages-query")
.click(
function() {
var datatables_options = {
"aLengthMenu" : [ [ 5, 10, 50, 100,500, -1 ],[ 5, 10, 50, 100,500, "All" ] ],
"iDisplayLength" : 5,
//The following SDOM, 1.9 version will not show up
"sDom": 'T<"clear">rt<"float_left"i><"float_right_nexpage"p><"float_right_display"l>',
//"sDom" : "<r>t<'float_left'i><'float_right_nexpage'p><'float_right_display'l>>",
"bSort" : false,
"bProcessing" : false,
"bServerSide" : true,
"bStateSave" : true,
"bDestroy" : true,
"bDeferRender":true,
"bJQueryUI" : false,
"sScrollX" : "100%",
"bStateSave":true,
"language" : oLanguageData,
// "aaData" : data,
"aoColumns" : aoColumnsData,
"fnRowCallback" : function(nRow, aData,
iDataIndex) {
},
"sAjaxSource" : "wageQuery.action?wageDate="
+ date,
"fnServerData" : function(sSource, aoData,
fnCallback) {
$.ajax({
"type" : 'post',
"async":false,
"url" : sSource,
"dataType" : "json",
"data" : aoData,
"success" : function(resp) {
fnCallback(resp);
}
});
},
"fixedColumns": {
"iLeftColumns" : 4,
"sHeightMatch" : "auto"
},
};
//Determine whether the table has been an instance, there is no instance, has been a direct update, load the corresponding URL
if (typeof(wageNowTable) == "undefined") {
wageNowTable = $('#sample_1').dataTable(datatables_options);
}else{
var oSettings = wageNowTable.fnSettings();
oSettings.sAjaxSource = "wageQuery.action?wageDate="
+ date;
wageNowTable.fnDraw(false);//Don't jump to the first page, the page number and the reserved page displays the number of
wageNowTable.fnDraw(false);//
}
//Important point: listen to the state of the check box, the important need to use the form of on, the direct click can not change the state
$('.DTFC_LeftHeadWrapper div').on('click','input' ,function () {
$("#uniform-check-all").removeClass("checker");
$("span").removeClass("checked");
var val = $(this).prop("checked");
$("input[type='checkbox']", ".DTFC_LeftHeadWrapper").attr("checked", val);
$("#check-all").attr("checked", val);
if (val) {
$(".checkboxes").each(function(index){
$(this).attr("checked", val);
});
} else {
$(".checkboxes").each(function(index){
$(this).attr("checked", val);
});
}
} );
});
Determine whether the table has been an instance, there is no instance, has been a direct update, load the new URL:
if (typeof(wageNowTable) == "undefined") {
wageNowTable = $('#sample_1').dataTable(datatables_options);
}else{
var oSettings = wageNowTable.fnSettings();
oSettings.sAjaxSource = "wageQuery.action?wageDate="
+ date;
//need twice fndraw
wageNowTable.fnDraw(false);
wageNowTable.fnDraw(false);
}

Related

How am I able to get the column of the data in the DataTable where my button is at in ajax?

Hello I am fairly new to datatable and I would like to seek help in retrieving the User ID when I click the button and that would trigger another ajax call where it will do a POST method but I am unsure how it can be done within the script tag. Is this the right method to implement the data and the button? I really need some advice on this.
Here is my code :
<script>
uId = sessionStorage.getItem('uId')
username = sessionStorage.getItem('username')
var userListTable = $('#userListTable').dataTable({
'ajax': {
"type" : "GET",
"url" : "http://localhost:8080/Test-war/webresources/users/" + uId + "/retrieveUserList",
"dataSrc": ""
},
'columns': [
{title : "User ID", "data" : "id"},
{title : "Username", "data" : "username"},
{title : "Gender", "data" : "gender"},
{title : "Email", "data" : "email"},
{title : "Contact", "data" : "contact"},
{title : "Created", "data" : "created", "render" : function(data) {
var date = new Date(data);
var month = date.getMonth() + 1;
return (month.toString().length > 1 ? month : "0"
+ month) + "/" + date.getDate() + "/" + date.getFullYear();
}},
{title : "Follow User", "defaultContent" : '<button onclick="followUser()">Follow User</button>'},
{title : "Unfollow User", "defaultContent" : '<button onclick="unfollowUser()">Unfollow User</button>'},
]
});
</script>
From here I am using a function followerUser() but I have no idea how am I able to get the tId of the row that the button was clicked at.
function followUser() {
var tId =
$.ajax({
type: "POST",
url: "http://localhost:8080/Test-war/webresources/users/" + tId + "/followUser",
data: body,
contentType: "application/json; charset=utf-8",
success: function(data, textStatus, xhr)
{
alert("You have successful followed user")
window.location.href = "viewUserList.html";
console.log(data)
console.log(textStatus)
},
error: function(xhr, error, errorType) {
alert("Error following user...")
}
});
Here is the image of the datatable :
You can use something like below code. you can use datatable API to fetch row data.
var dataSet = [
{'engine':'Webkit','browser':'Safari 1.2','platform':'OSX.3','version':'125.5','grade':'A'},
{'engine':'Other browsers','browser':'All others','platform':'-','version':'-','grade':'U'}
];
$(document).ready(function() {
$('#demo').html('<table class="display" id="example"></table>');
$('#example').dataTable( {
"data": dataSet,
"columns": [
{ "sortable" : false, "data": null, "defaultContent": "<button>Select</button>", "title" : "Choose"
},
{ "title": "Engine", "data": "engine" },
{ "title": "Browser", "data": "browser" },
{ "title": "Platform", "data": "platform" },
{ "title": "Version", "data": "version", "class": "center" },
{ "title": "Grade", "data": "grade", "class": "center" },
{ "defaultContent": true, "data": "existing", "visible": false }
],
initComplete: function(oSettings, json) {
console.log('drawing complete');
if (oSettings.fnRecordsTotal() > 1) {
$('#example').DataTable().row.add({
'engine' : 'Presto',
'browser' : 'Opera 7.5',
'platform' : 'Win 95+ / OSX.2+',
'version' : '-',
'grade' : 'A',
'existing' : false
}).draw();
}
}
} );
$('#example tbody').on('click', 'button', function(e) {
var data = $('#example')
.DataTable()
.row( $(this).parents('tr') )
.data();
console.log(data.version);// obj.columnname you can use data.id in you case to fetch User id
});
});
here is working example

Conditional checking of "datatable checkboxes" in jQuery

Hi I'm trying to create a table that consists of checkboxes. And each row has its own class and ID.
$('#niisPrprtyCoverageTable').dataTable({
"data" : coverageList,
"columns" : [ {
"data" : "seqNo",
"visible" : false
}, {
"data" : "coverageCode"
}, {
"data" : "coverageName"
}, {
"data" : "coverageCode",
"width" : "80px",
"className" : "text-center",
render : function(data, type, row) {
var arrData = data.split(";");
var coverageCd = arrData[0];
var coverageRel = nvl(arrData[1], coverageCd);
data = '<input class="'+coverageRel+'" id="'+coverageCd+'" type="checkbox" onClick="addToArray('
+ coverageCd
+ ','
+ coverageRel
+ ')">';
return data;
}
} ],
"searching" : false,
"bLengthChange" : false,
"iDisplayLength" : 15 ,
"bSort" : false,
"columnDefs" : [ {
"targets" : [ 1, 2 ],
"className" : "left"
}, {
"targets" : [ 2 ],
"width" : "150px",
}, {
"targets" : [ 1 ],
"width" : "100px",
}, {
"targets" : [ 3 ],
"width" : "50px",
"className" : "text-center"
} ]
});
niisPrptyCoverageTable = $('#niisPrprtyCoverageTable').DataTable();
$('#select-all').on('click', function(){
alert('ss');
// Get all rows with search applied
var rows = niisPrptyCoverageTable.rows({ 'search': 'applied' }).nodes();
// Check/uncheck checkboxes for all rows in the table
$('input[type="checkbox"]', rows).prop('checked', this.checked);
});
What should happen is, if I check the main row, all the rows under his 'code or id' should be checked also.
It works but only on the first page
but doesn't work on the second page of the datatable
var array = [];
function addToArray(coverageCd, coverageRel) {
var rows = niisPrptyCoverageTable.rows('.'+coverageRel).nodes().className;
$('input[class='+coverageCd+']', rows).prop('checked', '#'+coverageCd.checked);
}
Use $() API method to get access to elements on all pages, not just current page.
For example:
var array = [];
function addToArray(coverageCd, coverageRel) {
var rows = niisPrptyCoverageTable.rows('.'+coverageRel).nodes().className;
niisPrptyCoverageTable.$('input[class='+coverageCd+']', rows).prop('checked', '#'+coverageCd.checked);
}
Alternatively see jQuery DataTables Checkboxes extension for easier handling of checkboxes in a table powered by jQuery DataTables.

JS - jQuery.fn.DataTable is undefined

I'm trying to use datatables to display a list of records in two different pages.
Problem is the first datatable works while the second one (that's a perfect clone of the first) doesn't...
The issue is related to $.fn.DataTable: in the first case it exists so the script goes on filling the datatable while in the second case it is undefined.
The "big" problem here is that both the datatables are perfectly the same. What changes are the ids and the content...
These are the two scripts I'm using to populate the datatables:
transactionsHistoryInit : function($) {
var datatable = $('#transactions-history-table');
if (datatable.length > 0 && typeof $.fn.DataTable !== "undefined") {
datatable.DataTable({
"responsive" : true,
"searching" : false,
"processing" : true,
"serverSide" : true,
"pageLength" : 20,
"lengthChange" : false,
"stateSave" : true,
"pagingType" : "full_numbers",
"info" : false,
"columnDefs" : [ {
"orderable" : false,
"targets" : [ 1, 2, 3, 4 ]
} ],
"ajax" : {
"url" : siteData.ajaxurl + "?action=transactions_history",
"type" : 'POST'
},
"language" : {
"url" : siteData.ajaxurl
+ "?action=datatable_internazionalization"
}
});
transactionStartDate.datetimepicker({
"locale" : transactionStartDate.data("locale")
});
transactionEndDate.datetimepicker({
"locale" : transactionEndDate.data("locale"),
"defaultDate" : new Date()
});
transactionStartDate.add(transactionEndDate).on("dp.change",
function(e) {
datatable.draw();
});
}
},
bankToBankAccountChoice : function($) {
var datatable = $('#bank-account-table');
if (datatable.length > 0 && typeof $.fn.DataTable !== "undefined") {
datatable.DataTable({
"responsive" : true,
"searching" : false,
"processing" : true,
"serverSide" : true,
"pageLength" : 10,
"lengthChange" : false,
"stateSave" : true,
"pagingType" : "full_numbers",
"info" : false,
"ajax" : {
"url" : siteData.ajaxurl
+ "?action=bank_to_bank_account_choice",
"type" : 'POST'
},
"language" : {
"url" : siteData.ajaxurl
+ "?action=datatable_internazionalization"
}
});
}
}
I was also getting $.fn.dataTable as undefined
In my case, I was loading jquery multiple times. Jquery must be loaded only once.

How to remove selected existing data and add new row without affecting other rows in Jquery data table

I have 100 rows of data, i want to remove selected data based on ID and add new row for that ID. I want to edit the rows based on ID.
Here is my code:
oCustomization : {
sExportFunctionCall : oMapUrls.exportLiveFleetReport,
bAdvanceExport : true,
bShowDefaultAll : !bLivePaginate
},
pageLength : !bLivePaginate ? -1 : Global.rowLength,
scrollCollapse : false,
scrollY : iDataTableHeight,
serverSide : bLivePaginate,
order : [ [ 3, "desc" ] ],
columns : [
{
"data" : "trackeeName",
"width" : aColumnWidths[0],
"class" : "no-word-break",
"settings" : {
source : function(request, oCallback) {
oCallback($.ui.autocomplete.filter(Global.aJSTreeVehicleItems || [], request.term));
}
},
"render" : function(value, type, rowData) {
//Some code here
}
},
{
"data" : "firstName",
"width" : aColumnWidths[1],
"class" : "no-word-break",
settings : {
source : Global.getDriverSuggestion
},
"title" : jQuery.i18n.prop("driver.title.txtInfo"),
"visible" : Global['show.driver.in.reports'] == 1,
"render" : function(value, type, rowData) {
return getUserName(rowData.firstName, rowData.lastName);
}
},
{
"data" : "groupName",
"width" : aColumnWidths[2],
"class" : "no-word-break",
"settings" : {
source : function(request, oCallback) {
oCallback($.ui.autocomplete.filter(Global.aJSTreeGroupItems || [], request.term));
}
},
"title" : jQuery.i18n.prop("vehicle.col2label")
},
{
"data" : "dateAndTime",
"width" : aColumnWidths[3],
"searchable" : !bLivePaginate,
"class" : "wordBreak",
"title" : jQuery.i18n.prop("report.columnTitle.date"),
"render" : function(value, type, rowData) {
if (type == "display") {
return rowData.formattedDate;
}
return value;
}
}
I get data in JSON format. I want to remove selected rows , it should not affect other rows data.
Simply use WHERE
DELETE FROM DBNAME WHERE ID=XXX
then Insert into the table with that ID
however, if you want to delete and insert together always, an UPDATE query will work better

Data Table Server Side Processing

Hi i am using datable server side processing,
$(document).ready(function() {
$("#TABLE").dataTable({
"bProcesing" : true,
"bServerSide" : true,
"bLenthChange" : false,
"iDisplayLength" : 10,
"bSort":false,
"bFilter": true,
"sAjaxSource" : "/easdaspp/abc",
"aoColumns" : [
{
"sTitle" : "Organization Name",
"mData" : "organizationName"
},
{
"sTitle" : "Delete",
"sDefaultContent" : '<a href="abc/{organizationId}" >Delete</a>'
}],
"fnServerData" : function(sSource, aoData, fnCallback) {
$.ajax({
"dataType" : 'json',
"type" : "GET",
"url" : sSource,
"data" : aoData,
"success" : fnCallback
});
},
"sPaginationType" : "full_numbers"
});// dataTable
});
How do i get organizationId value in anchor tag
like this
"sDefaultContent" : '<a href="abc/{organizationId}" >Delete</a>'
should be
<a href="abc/1" >Delete</a>
so on for every rows, the value of url should change according to us
Well I use another method see for yourself
this is the server side script of the old datatables
static function data_output($columns, $data) {
$out = array();
for ($i = 0, $ien = count($data); $i < $ien; $i++) {
$row = array();
for ($j = 0, $jen = count($columns); $j < $jen; $j++) {
$column = $columns[$j];
if ( $aColumns[$i] == "cId" ){
/* Special output formatting for 'cId' column */
$row[] = '
<div id="trigger">
<a target="_blank" title="Click to make Payment" href="viewDetails.php?cId='.$aRow[$aColumns[$i]].'">
<img src="images/icons/color/rupee.png" />
</a>
</div>
';
}
}
}
I got the solution using mRender we can sort this out
{"mData" : "organizationId",
"mRender": function ( data, type, full ) {
return 'Download';
}

Categories