Using sAjaxSource works, but setting the aaData myseld does not - javascript

When I'm using DataTables with sAjaxSource it works, but when doing the ajax upfront, and setting the aaData property I get error. Any ideas?
This method works:
// This method works fine
$('#spiderData').dataTable({
"bProcessing": true,
"sAjaxSource": "spiderOrders.cshtml?GetOrders=true&pid=" + pid + "&itemid=" + itemId + "&signatur=" + signatur + "&orderid=" + orderid + "&type=signatur",
"aoColumns": [
{ "mDataProp": "BuildOrderId" },
{ "mDataProp": "description" },
{ "mDataProp": "BuildProductOrderId" },
{ "mDataProp": "state_desc" },
{ "mDataProp": "buildProductName" },
{ "mDataProp": "program" },
{ "mDataProp": "KP_BPO" },
{ "mDataProp": "WorkOrderId" },
{ "mDataProp": "title" },
{ "mDataProp": "state_desc" },
{ "mDataProp": "contractorName" },
{ "mDataProp": "TP" }
]
});
But this does not:
// This is not working, why????
$.ajax({
type: 'GET',
url: "spiderOrders.cshtml?GetOrders=true&pid=" + pid + "&itemid=" + itemId + "&signatur=" + signatur + "&orderid=" + orderid + "&type=signatur",
data: "jalla",
success: function (data) {
$('#spiderData').dataTable({
"bProcessing": true,
"aaData": data,
"aoColumns": [
{ "mDataProp": "BuildOrderId" },
{ "mDataProp": "description" },
{ "mDataProp": "BuildProductOrderId" },
{ "mDataProp": "state_desc" },
{ "mDataProp": "buildProductName" },
{ "mDataProp": "program" },
{ "mDataProp": "KP_BPO" },
{ "mDataProp": "WorkOrderId" },
{ "mDataProp": "title" },
{ "mDataProp": "state_desc" },
{ "mDataProp": "contractorName" },
{ "mDataProp": "TP" }
]
});
}
});
In case of the first example data returned has this format:
{ "aaData": [
{
"BuildOrderId":"S2008-015758.001",
"description":"Hordaland-Bergen-ALH4 - Leveranse av 2 Mb",
"BuildProductOrderId":"S2008-015758.002", .....
And in the second example this format:
[{"BuildOrderId":"S2008-006891.001","description":"MXJP81, BERSTADHUSETMOB, HOR-00323","BuildProductOrderId":"S2008-006891.002", ....
Am I missing something, or formatting the response wrong (I've checked a few times now...)

Why is it important to do it the second way? If you need access to all that .ajax has to offer (more flexibility in variables vs the default .getJSON) you can still do that with the fnServerData parameter.
That said, what's probably wrong with the second way is that you're trying to use "data" directly. It needs to be parsed first.
"aaData": $.parseJSON(data).aaData,
disclaimer: I haven't tested this and prefer the fnServerData method

Related

load custom response in datatable using server side processing

I am trying to load datatable from ajax response and then perform server-side processing. using this example
this is the response I am receiving from server :
{"msg":null,"code":null,"status":null,"result":[{"aNumber":"3224193861","bNumber":"3215910681","dateTime":"2017-06-05 09:44:22.0","duration":778,"imei":"47350901163665"},{"aNumber":"3224193861","bNumber":"3028540439","dateTime":"2017-04-26 18:53:23.0","duration":266,"imei":"31489802062929"}],"draw":1,"limit":1000,"recordsFiltered":13419,"recordsTotal":13419}
this my javascript code to handle ajax and datatable.
function showDataTable(anumber, startdate, enddate) {
var cdrReqParams = {};
cdrReqParams.draw = '1';
cdrReqParams.offset = 0;
cdrReqParams.newRequest = '1';
cdrReqParams.totalRecords = '1';
cdrReqParams.lookInCol = 'aNumber';
cdrReqParams.lookInVal = anumber;
cdrReqParams.fromDate = startdate;
cdrReqParams.toDate = enddate;
var jsonStr = JSON.stringify(cdrReqParams);
console.log(jsonStr);
API.call("http://localhost:8050/phpservice/json.php", 'POST', function(data) {
basicData = data.result;
console.log(basicData);
oTable = $("#table").dataTable({
bJQueryUI: true,
bPaginate: true,
sPaginationType: "full_numbers",
bFilter: false,
bInfo: false,
bProcessing: true,
bServerSide: true,
aaData: [basicData],
aoColumns: [{
"sTitle": "ANUMBER",
"mData": "aNumber"
}, {
"sTitle": "BNUMBER",
"mData": "bNumber"
}, {
"sTitle": "DATETIME",
"mData": "dateTime"
}, {
"sTitle": "DURATION",
"mData": "duration"
}, {
"sTitle": "IMEI",
"mData": "imei"
}]
});
}, function(error) {
console.log(error);
}, jsonStr);
}
By doing this, I am receiving 2 errors
DataTables warning: table id=table - Requested unknown parameter
'aNumber' for row 0, column 0. For more information about this error,
please see http://datatables.net/tn/4
and
Invalid JSON Response.
Is there any workaround for this type of problem, In which first, you will perform ajax call and from received data, you will populate datatable with server side processing ??
I hope someone will give me a hint at least.
With datatable 1.10,(i think you may be using an earlier version), you can populate and format the data in the cells, by using the columns.data property:
columns: [
{ data: "", defaultContent: " " },
{ data: null,
defaultContent: " ",
render: function (data, type, row, meta) {
return data.ID;
}
}
]

Datatables initialization warning

I have a dropdown with multiple options that initializes a datatable using javascript. Everything works fine but the problem comes during execution in which when the option is selected second time i get an error , check out this fiddle,
DataTables warning (table id = 'defDiv'): Cannot reinitialise DataTable.
And Below is my code :
if(user.position=="DEF"){
var table = $('#defDiv').DataTable({
"aaData":defenders,
"iDisplayLength":15,
"aoColumns": [
{ "mDataProp": "playerInfo" },
{ "mDataProp": "playerName" },
{ "mDataProp": "playerClub" },
{ "mDataProp": "playerValue" },
{ "mDataProp": "playerPoints" },
],
"order": [[ 3, "desc" ]],
});
}
Question is how can i prevent the warning from happening when the option is selected again ?
I've altered you code and it works now:
var goalkepeers = [{
"playerName": "Mignolet",
"playerClub": "Liverpool",
"playerValue": "5.0",
"playerPoints": "89",
}, {
"playerName": "de Gea",
"playerClub": "Manchester",
"playerValue": "6.7",
"playerPoints": "120",
}];
var defenders = [{
"playerName": "Ivanovic",
"playerClub": "Chelsea",
"playerValue": "7.8",
"playerPoints": "100",
}, {
"playerName": "Mertesacker",
"playerClub": "Arsenal",
"playerValue": "7.7",
"playerPoints": "110",
}];
var aoColumns = [{
"sTitle": "Name",
"mDataProp": "playerName"
},{
"sTitle": "Club",
"mDataProp": "playerClub"
},{
"sTitle": "Value",
"mDataProp": "playerValue"
},{
"sTitle": "Points",
"mDataProp": "playerPoints"
}];
var table = null;
$("#playersFilter").change(function () {
var value = $('#playersFilter').val();
if (value == "gk") {
if ($.fn.dataTable.isDataTable('#players')) {
$('#players').DataTable().destroy();
}
table = $('#players').DataTable({
"aaData": goalkepeers,
"iDisplayLength": 15,
"aoColumns": aoColumns,
"bRetrieve": true,
"order": [
[3, "desc"]
],
"bDestroy": true
});
} else if (value == "def") {
if ($.fn.dataTable.isDataTable('#players')) {
$('#players').DataTable().destroy();
}
table = $('#players').DataTable({
"aaData": defenders,
"iDisplayLength": 15,
"aoColumns": aoColumns,
"bRetrieve": true,
"order": [
[3, "desc"]
],
"bDestroy": true,
});
}
});
I'm pretty sure there's a more efficient way of doing it, I'll have a think and post a link to a JSFiddle as a comment.
You only really need the one table as well:
<select id="playersFilter">
<option>Choose Players</option>
<option value="gk">goalkepeers</option>
<option value="def">Defenders</option>
</select>
<table class="display" id="players"></table>
use this code
if(user.position=="DEF"){
var table = $('#defDiv').DataTable({
"aaData":defenders,
"iDisplayLength":15,
"aoColumns": [
{ "mDataProp": "playerInfo" },
{ "mDataProp": "playerName" },
{ "mDataProp": "playerClub" },
{ "mDataProp": "playerValue" },
{ "mDataProp": "playerPoints" },
],
//EDITS
"bRetrieve":true,
"order": [[ 3, "desc" ]],
// use this in your code
"bDestroy": true,
});
}
this will work for me &
more details
Can you just destroy the table prior to re-initialization?
table.DataTable().destroy();
Something like this:
var table;
if ($.fn.dataTable.isDataTable('#defDiv')) {
table.DataTable().destroy();
}
table = $('#defDiv').DataTable({...
Documentation can be found here
Demo here

How to get checked row ids in jQuery DataTables

In the below code I have a jQuery DataTable and I want to get selected row ids and store it into array. But I get only one row id SchoolID but I want to get SchoolID, ClassID and SectionID for checked checkbox.
var val[]; //global
"aoColumns": [
{
"mDataProp": "SchoolID",
"bSearchable": false,
"bSortable": false,
"sWidth": "10%",
"mRender": function(data, type, full) {
val = '<input type="checkbox" id="chkSchoolID" onclick="CheckRow(' + full.SchoolID + ')"></button>';
return val;
}
},
{
"mDataProp": "SchoolID",
"sWidth": "25%"
}, {
"mDataProp": "ClassID",
"sWidth": "25%"
}, {
"mDataProp": "SectionID",
"sWidth": "25%"
},
],
function CheckRow() {
alert(val);
}

Uncaught TypeError: Object [object Object] has no method 'fnFilterClear'

I am getting this error in the console :
"Uncaught TypeError: Object [object Object] has no method 'fnFilterClear'"
My code :
$(document).ready(function () {
var selectedColumn = $('#columnlist').find(":selected").text();
$('#csearchtext').bind("change paste keyup", function () {
var input = $('#csearchtext').val();
var dropdownindex = $("select[name='columnlist'] option:selected").index();
console.log(dropdownindex);
$('#table_id').dataTable().fnFilter(input, dropdownindex + 1, false, true, true, false);
});
$('#columnlist').on('change', function () {
$('#table_id').dataTable().fnFilterClear();
});
$('#dblist').on('change', function () {
var selected = $('#dblist').find(":selected").text();
tablefill(selected);
});
$('#search').click(function () {
var selected = $('#dblist').find(":selected").text();
tablefill(selected);
});
function tablefill(selected) {
$('.advsearchbar').show();
$('#stable').show();
$('#table_id').dataTable({
"sAjaxSource": '/php/connect/searchtablequery.php',
"bProcessing": true,
"sScrollY": "500px",
"bDeferRender": true,
"bDestroy": true,
"sAjaxDataProp": "",
"fnServerParams": function (aoData) {
aoData.push({ "name": "db", "value": selected });
},
"aoColumns": [
{ "mData": "calldate" },
{ "mData": "recordingfile" },
{ "mData": "uniqueid" },
{ "mData": "src" },
{ "mData": "did" },
{ "mData": "lastapp" },
{ "mData": "dst" },
{ "mData": "disposition" },
{ "mData": "duration" },
{ "mData": "userfield" },
{ "mData": "accountcode"}],
"iDisplayLength": 20,
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"sDom": '<"H"Tfr>t<"F"ip>',
"oTableTools": {
"sSwfPath": "/DataTables/extras/TableTools/media/swf/copy_csv_xls_pdf.swf",
"aButtons": [
"copy", "csv", "xls", "pdf",
{
"sExtends": "collection",
"sButtonText": "Save",
"aButtons": ["csv", "xls", "pdf"]
}]
}
});
}
});
The javascript is firing just fine but the one spot that triggers the fnfilterclear has that error prompted.
Look at http://datatables.net/plug-ins/api#how_to How to use Datatable Plug-in API. You have to include the function listed on that page to use the function.
To make use of one of the plug-in API functions below, you simply need to include it in the Javascript available for your page, after you load the DataTables library, but before you initialise the DataTable. After that, you will be able to initialise the table, and call the function on the resulting object.

Undefined Object in DataTable

Have a datatable and using the drill down row. The top row populate data but the link to drill down to the additional row contains a undefined object and I'm stuck right there.
Any help would be so appreciated. oData.code (undefinded) / oData itself will return everything from the linq query but when I start using the oData.etc... the object becomes undefined. Even in the click event I've tried to access oData and drop it in the second TD row and it to is also undefined.
function fnFormatDetails(oTable, nTr)
{
var oData = oTable.fnGetData(nTr);
var sOut =
'<div>' +
'<table>' +
'<tr><td> '+oData.code+' </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>'
'</table>' +
'</div>';
return sOut;
} //end fnFormatDetails function
$(document).ready(function ()
{
var anOpen = [];
var oTable = $('#VADataTable').dataTable(
{
"sDom": 'T<"clear">lfrtip',
"oTableTools":
{
"sSwfPath": "/swf/copy_csv_xls_pdf.swf"
}, //flash must be enabled
"iDisplayLength": 5, //defalut amount of rows shown on page
"bServerSide": false, //uses sever for filter curently turned off
"bFilter": false, //makes columns clickable to filter
"bProcessing": true,
"bserverSide":false,
"bJQueryUI": true, //enables user interface
"bSort": true, //sorting for columns
"bScrollInfinite": true, //using this takes away ddl of selection
"sAjaxSource": "Data/IndustryTable", //where ajax commands renders results
"sScrollY": "200px",
"sScrollX": "100%",
"sScrollXInner": "100%",
"bScrollCollapse": true,
"fnRowCallback": function (nRow, aData)
{
if (aData[0] == "")
{
$('td:eq(0)', nRow).html("+").addClass('control');
}
return nRow;
}, //ends fnRowCallback
"aoColumns":
[
{ "sName": "code", "sTitle": "Code" },
{ "sName": "code" },
{ "sName": "data" },
{ "sName": "data" },
{ "sName": "data" },
{ "sName": "data" },
{ "sName": "data" }
]
});
$('#VADataTable td.control').live('click', function ()
{
var nTr = this.parentNode;
var i = $.inArray(nTr, anOpen);
if (i === -1)
{
$('td').attr('+');
var nDetailsRow = oTable.fnOpen(nTr, fnFormatDetails(oTable, nTr), 'details');
$('div', nDetailsRow).slideDown();
anOpen.push(nTr);
} //end if
else
{
$('td').attr('-');
$('div', $(nTr).next()[0]).slideUp(function ()
{
oTable.fnClose(nTr);
anOpen.splice(i, 1);
}); //ends slideUp
} //ends else
$('#new tr').after('<td> '+ typeof(oTable.code) +' </td>');
}); //ends click event
} //ends live event
)//ends ready function
I believe that just add the "mData" property in "aoColumns", that is the name of fields of database table, and in "fnRowCallback" you must replace "aData[0]" by "aData['code']" like the next example:
"fnRowCallback": function (nRow, aData)
{
if (aData['code'] == "")
{
$('td:eq(0)', nRow).html("+").addClass('control');
}
return nRow;
}, //ends fnRowCallback
"aoColumns":
[
{ "mData" : "code", "sName": "code", "sTitle": "Code" },
{ "mData" : "code", "sName": "code" },
{ "mData" : "data", "sName": "data" },
{ "mData" : "data", "sName": "data" },
{ "mData" : "data", "sName": "data" },
{ "mData" : "data", "sName": "data" },
{ "mData" : "data", "sName": "data" }
]

Categories

Resources