Trying to access dataTable variable outside ajax is giving undefined - javascript

I have a jquery autocomplete that once a value is selected it loads a datatable with checkbox from an ajax call. Then while submitting the form I need to access the datatable variable to iterate each row to get the selected ones, but the datatable variable appears as undefined.
I'm doing the same as in this example, only difference is the data is coming from an Ajax request.
Can you please help me understand why is that happening?
$(document).ready(function() {
var campId;
var t_OmnitureCode;
// Campaign input autocomplete
$("#campaign").autocomplete({
source: function(request, response) {
$.ajax({
url: "promotion",
type: "GET",
data: {
term: request.term,
action: "searchCampaign"
},
dataType: "json",
success: function(data) {
if (!data.length) {
var result = [{
label: "no match found",
value: "-1"
}];
response(result);
} else {
response($.map(data, function(item) {
return {
label: item.name,
value: item.campaignId
}
}));
}
}
});
},
select: function(event, ui) {
event.preventDefault();
campId = ui.item.value;
if (campId != "-1") {
this.value = ui.item.label;
// This will apply datatables getting the content from an Ajax call
t_OmnitureCode = applyDataTableOmnitureCode(campId);
}
},
focus: function(event, ui) {
event.preventDefault();
this.value = ui.item.label;
}
});
// Handling form submission
$("#frm_promotion").on("submit", function(e) {
var form = this;
// Variable for datatable "t_OmnitureCode" is undefined below
var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();
EDIT:
Just realized that even while assigning the variable (t_OmnitureCode = applyDataTableOmnitureCode(campId);) it is undefined, not sure why.
Here is the applyDataTableOmnitureCode code:
function applyDataTableOmnitureCode(campId) {
$("#tbl_omnitureCode").DataTable({
destroy: true,
scrollX: true,
fixedColumns: {
leftColumns: 1
},
"ajax": {
"url": "promotion",
"type": "GET",
"data": {
action: "searchOmnitureCodesByCampaignId",
campaignId: campId
},
"dataSrc": ""
},
"columns": [
{ "data": "key" },
{ "data": "omnitureCode" },
{ "data": "urlAppName" },
{ "data": "language" },
{ "data": "channel" },
{ "data": "createDateTime", "defaultContent": "" },
{ "data": "updateDateTime", "defaultContent": "" }
],
"columnDefs": [
{ "targets": 0, "checkboxes": { "selectRow": true } }
],
"select": {
"style": "multi"
},
"order": [[1, "asc"]],
"fnInitComplete": function() {
$("#omnitureCodeSection").show();
}
});
};

You may need to grab your DataTables object into a variable before using that:
var t_OmnitureCode = $("#tbl_omnitureCode").DataTable();
var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();
And, by the way, your method of populating DataTable with external ajax-call is suboptimal. There's an ajax option for that purpose where you can specify all the necessary parameters and get better integration with DataTables API and better performance (as you don't really need to destroy and create your DataTable upon each refresh).
You would simply need to trigger .ajax.reload() whenever you need to refresh your table data.

It's a matter of scope : You declare the variable table inside $(document).ready function.
You may want to put it outside in the global scope :
var table;
$(document).ready(function() {
table = $('#example').DataTable({
...
});

Related

Set default value before click event triggers

I have button groups. Once user clicks on the link, it filters value based on the content in the link. By default I added selected class. I want default value of link which contains selected class to be considered for filtering before click event triggers. It works fine when user clicks on c-btn-group but not considers default value when page loads. As of now it shows complete data without filtering when page loads.
<div class="c-btn-group">
<a class="c-btn selected">Large Cap</a>
<a class="c-btn">Small Cap</a>
<a class="c-btn">virginica</a>
</div>
JS
$('.c-btn-group').on('click', 'a', function(event) {
var searchTerm = this.textContent;
/* 4th column filtering */
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
if (data[3] == searchTerm) {return true;}
return false;
})
table.draw();
$.fn.dataTable.ext.search.pop();
// Add or remove 'selected' class;
event.preventDefault();
$('a').removeClass('selected');
$(this).addClass('selected');
});
Try the below script. Here is demo
Separate out logic of dataTable filtering inside filter function. Get selected text by $('.c-btn-group .selected').text(); and call filter(initialSelectedText);
var myList2;
$.ajax({
url: "https://raw.githubusercontent.com/markwsac/jsonfile/main/jsondata.json",
type: "get",
dataType: 'text',
async: false,
success: function(response) {
if (!response) return;
response = response.slice(0, -1); // trim ";" at the end
window.myList2 = JSON.parse(response);
},
error: function(err) {
console.log(err);
}
});
var myList = window.myList2;
$(document).ready(function () {
table = $("#mfTable").DataTable({
data: myList,
paging: true,
lengthChange: false,
searching: true,
info: false,
columns: [
{ data: 'Fund Name' },
{ data: 'Morningstar Rating' },
{ data: 'Category Rank' },
{ data: 'Category' },
{ data: 'Expense Ratio' },
{ data: 'AUM (Cr)' },
{ data: 'NAV' },
],
columnDefs: [{
"defaultContent": "-",
"targets": "_all"
}]
});
const initialSelectedText = $('.c-btn-group .selected').text();
filter(initialSelectedText);
$('.c-btn-group').on('click', 'a', function(event) {
var searchTerm = this.textContent;
/* 4th column filtering */
filter(searchTerm);
// Add or remove 'selected' class;
event.preventDefault();
$('a').removeClass('selected');
$(this).addClass('selected');
});
});
function filter(searchTerm){
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
if (data[3] == searchTerm) {return true;}
return false;
});
table.draw();
$.fn.dataTable.ext.search.pop();
}
DataTable provides an Option for this. When you are initializing your table, just use the searchCols option which would load the table with the initial search provided. for Example:
table = $("#mfTable").DataTable({
data: myList,
paging: true,
lengthChange: false,
searching: true,
info: false,
columns: [
{ data: 'Fund Name' },
{ data: 'Morningstar Rating' },
{ data: 'Category Rank' },
{ data: 'Category' },
{ data: 'Expense Ratio' },
{ data: 'AUM (Cr)' },
{ data: 'NAV' },
],
columnDefs: [{
"defaultContent": "-",
"targets": "_all"
}],
searchCols: [
null,
null,
null,
{ "search": "Large Cap" },
null,
null,
null,
]
})
Here is the link for this option https://datatables.net/reference/option/searchCols
You can also use the libraries own search method rather than implementing it yourself, so instead of writing:
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
if (data[3] == searchTerm) {return true;}
return false;
})
table.draw();
$.fn.dataTable.ext.search.pop();
just write:
table.column(3).search(searchTerm).draw();

Unable To Display Json Data in html Table Using jquery DataTable

i have C# function That Return Me Json Formated Data , function is below
void DisplayProjectMasterList()
{
string JSONString = "";
DataTable Dt = DB.GetDataTable("Sp_GetProjectMasterList");
if (Dt.Rows.Count > 0)
{
JSONString = JsonConvert.SerializeObject(Dt);
}
Context.Response.Write(JSONString);
}
and I am Calling This Function Via Ajax .in console i am getting json data But i dont know how to pass it to Jquery data table to display.. below is the javascript function... please help Me
function DisplayProjectMasterList() {
$.ajax({
url: 'project-master.ashx',
type: "POST",
dataType: 'json',
data: {
'fun': 'DisplayProjectMasterList'
},
success: function (data) {
console.log(data);
if (Chk_Res(data.errorMessage) == false) {
$('#tbl').dataTable({
paging: true,
sort: true,
searching: true,
scrollY: 200,
data: data,
columns: [
{ 'data':data.Prj_Id },
{ 'data':data.Prj_No },
{ 'data':data.Prj_Name },
{ 'data':data.Cus_Company_Name },
{ 'data':data.Prj_StartDate },
{ 'data':data.Prj_CompletionDate },
]
});
}
}
});
}
i am Getting FOllowing error while doing So:
DataTables warning: table id=tbl - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
Hi make sure the data you are being returned is in the following format:
{
"data": [
{
"Prj_Id": 1,
"Prj_No": 1,
"Prj_Name": "name",
"Cus_Company_Name": "company",
"Prj_StartDate": "2011/04/25",
"Prj_CompletionDate": "2011/04/25"
},
{
"Prj_Id": 1,
"Prj_No": 1,
"Prj_Name": "name",
"Cus_Company_Name": "company",
"Prj_StartDate": "2011/04/25",
"Prj_CompletionDate": "2011/04/25"
}
]
}
jquery Datatables by default looks for data property for the array of objects
https://datatables.net/reference/option/ajax.dataSrc
https://datatables.net/examples/ajax/objects.html

Datatables: dynamic page load in modal, based on row values

I am trying something really complex here, and I have not worked out a way to implement a solution yet. The part I work on looks like this:
1. simple page A that dynamically loads datatable from db.Last col is a button.
2. an html page B that loads different things according to 2 values stored at at local storage. these are available in the aforementioned table.
Now the part I cannot figure out:
3. Into the simple page A, there is a modal div. I want to load the B page into this modal on button click, and load different data, according to the values stored at local storage.
Here is my code so far:
function getadminprojects(){ //function that dynamically loads datatable
$.ajax({
url: "http://....../CustomServices/DBDistApps",
type: "GET",
dataType: 'json',
async: false,
success: function(data) {
$('#projectsdt').show();
projectsTable = $('#projectsdt').DataTable({
"pageLength": 10,
"data": data,
"scrollX": true,
"order": [[ 4, "desc" ]],
//"aaSorting": [],
"columns": [
{ "data": "code" },
{ "data": "descr" },
{ "data": "manager" },
{ "data": "customer" },
{ "data": "link_date" },
{ "data": "delink_date"},
{ "data": "type"},
{
"data": null,
"defaultContent": "<button class='btn btn-warning' onclick='openmodal2();'>button1</button>"
},
{
"data": null,
"defaultContent": "<button class='btn btn-success' onclick='localStorage.setItem('username',"+row.customer+");localStorage.setItem('projectid',"+row.code+"); projectpopmodal(); '>button2</button>"
},
] ,
});
$('#projectsdt thead').on('click', 'tr', function () {
var data2 = table.row( this ).data();
alert( 'You clicked on '+data2[0]+'\'s row' );
} );
$('#projectsdt').show();
$('#projectsdt').draw();
}
});
}
function projectpopmodal(){
$('#showfreakinmap').load('newprojects.html');
$('#fsModal').modal('show');
}//function to load page B into modal of page A
Thank you in advance!

IF else like at datatable jquery

How could I perform If else like method in datatable? The variable 'data' returns the value of the variable, which is correct, but if it is blank, it would return the word "from1", "from2" which is supposed to be the value of the variable "from1". Am I doing the right approach or do you have any suggestion as workaround in this problem? thank you for your answers. here is my code:
var table = $('#records').DataTable({
type: 'post',
"ajax": "getHumanTrainings",
"bPaginate": true,
"bProcessing": true,
"pageLength": 10,
"columns": [{
mData: 'tdesc'
}, {
data: "fdDateFrom2",
defaultContent: 'from1'
}, {
data: "fdDateTo2",
defaultContent: 'from2'
}, {
data: "fcTrainor2",
defaultContent: 'train1'
}, {
mData: 'dur'
}]
});
I'd use the render option for the column data that you have, its much more flexible in terms of wanting something to be displayed by default.
var table = $('#records').DataTable({
type: 'post',
"ajax": "getHumanTrainings",
"bPaginate": true,
"bProcessing": true,
"pageLength": 10,
"columns": [{
mData: 'tdesc'
}, {
data: "fdDateFrom2",
render: function(data, type, row) {
// Check if blank
if (data === "") {
return row[<index for from1>]; // Just use the index for from1
}
// If not blank display data normally
return data;
}
}, {
data: "fdDateTo2",
render: function(data, type, row) {
// Check if blank
if (data === "") {
return row[<index for from2>]; // Just use the index for from2
}
// If not blank display data normally
return data;
}
}, {
data: "fcTrainor2",
render: function(data, type, row) {
// Check if blank
if (data === "") {
return row[<index for train1>]; // Just use the index for train1
}
// If not blank display data normally
return data;
}
}, {
mData: 'dur'
}]
});
I've left comments to give you a guide since I'm not familiar with your data, I would suggest printing out your row first over at render so you'd know which index to use.

Tabbing doesnt work for datatable

I m using jquery datatables in many pages and its working good in every page and in a single page its not working properly, i mean when i use tab to go through datatable, it works fine for the first time and when i try to do the same for second time, if i try to focus on any thing in few seconds in data table, the focus disappears and the foucs starts from the starting of the page.
Here goes the code
function tableCall(){
var clientId = $('#clientId').val();
var versionCount = $('#versionCount').val();
var fromDate = $('#fromDate').val();
var toDate = $('#toDate').val();
$.ajax({
url: auditTrail.props.reporttableURL,
type: "POST",
dataType: "json",
data: {
clientId:clientId,
versionCount:versionCount,
fromDate:fromDate,
toDate:toDate
},
success: function (data) {
searchJSON = data.data;
var len=searchJSON.length;
if (len > 0){
$('.no-data, #warning-sign').hide();
createTable();
}else{
$('.no-data').hide();
$('#warning-sign').show();
}
}
});
}
function createTable() {
wwhs.setADAAttrDynamic($('#auditTable'));
if ($.fn.DataTable.isDataTable('#auditTable')) {
// table.destroy();
$("#auditTable tbody").empty();
}
table = $('#auditTable').dataTable({
"searching":false,
"destroy":true,
"autoWidth": false,
"ordering": true,
"destroy":true,
"stateSave": true,
"drawCallback": attachEvents,
"stateLoadParams": function (settings, data) {
return false;
},
data: searchJSON,
columns: [{
data: "reportName"
}, {
data: "reportStatus"
}, {
data: "timeStamp"
}, {
data: "requestedBy"
}],
"columnDefs": [{
"render": function (data, type, row) {
if(row.reportStatus.toUpperCase() == 'PROCESSED')
return '<a class="blue-text" " data-name="'+ row.reportName +'">' + row.reportName + '</a>';
else
return row.reportName;
},
"width": "50%",
"targets": 0
}, {
"width": "15%",
"targets": 1
}, {
"width": "20%",
"targets": 2
}, {
"width": "15%",
"targets": 3
}]
});
}
I think the problem is because the datatable instance is not destroyed.
Since datatables saves all the nodes into an object and renders it when ever it wants, emptying the tbody doesnt do anything. it just removes the elements in the page which can be re-drawn/re-rendered by datatable from its stored object.
You can check if the object is already initialized and the destroy it before re-initializing.
if(typeof table != "undefined")
table.destroy();
So the final code will look something like
function tableCall(){
var clientId = $('#clientId').val();
var versionCount = $('#versionCount').val();
var fromDate = $('#fromDate').val();
var toDate = $('#toDate').val();
$.ajax({
url: auditTrail.props.reporttableURL,
type: "POST",
dataType: "json",
data: {
clientId:clientId,
versionCount:versionCount,
fromDate:fromDate,
toDate:toDate
},
success: function (data) {
searchJSON = data.data;
var len=searchJSON.length;
if (len > 0){
$('.no-data, #warning-sign').hide();
createTable();
} else {
$('.no-data').hide();
$('#warning-sign').show();
}
}
});
}
function createTable() {
wwhs.setADAAttrDynamic($('#auditTable'));
if ($.fn.DataTable.isDataTable('#auditTable')) {
if(typeof table != "undefined")
table.destroy();
}
table = $('#auditTable').dataTable({
"searching":false,
"destroy":true,
"autoWidth": false,
"ordering": true,
"destroy":true,
"stateSave": true,
"drawCallback": attachEvents,
"stateLoadParams": function (settings, data) {
return false;
},
data: searchJSON,
columns: [{
data: "reportName"
}, {
data: "reportStatus"
}, {
data: "timeStamp"
}, {
data: "requestedBy"
}],
"columnDefs": [{
"render": function (data, type, row) {
if(row.reportStatus.toUpperCase() == 'PROCESSED')
return '<a class="blue-text" " data-name="'+ row.reportName +'">' + row.reportName + '</a>';
else
return row.reportName;
},
"width": "50%",
"targets": 0
}, {
"width": "15%",
"targets": 1
}, {
"width": "20%",
"targets": 2
}, {
"width": "15%",
"targets": 3
}]
});
}

Categories

Resources