load custom response in datatable using server side processing - javascript

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;
}
}
]

Related

API in javascript is returning data, but is not being saved into an array

I am trying to fetch data from an API of WordPress. Here is my code:
column.data().unique().sort().each(function (d,j) {
var practiceArea = d.practice_area;
var jsonPacticeArea = JSON.stringify(practiceArea);
if (jsonPacticeArea !== undefined) {
var res = $.map(jsonPacticeArea.split("|"), $.trim);
for (var i = 0; i < res.length; i++) {
var str = res[i];
str = str.replace(/"/gi, '').trim();
if (arrayPracticeArea.indexOf(str) === -1) {
arrayPracticeArea.push(str);
}
}
}
});
the "column" is the variable that is getting data through an API, and as far as I do console.log(column. data().unique().sort()), that's returning complete data as you can see in the screenshot:
[![enter image description here][1]][1]
and I want to fetch data is marked in red rectangle and store those values in an array, but as soon as I try to add "each" function to fetch the data and store it in an array (in my case its arrayPracticeArea) its returning undefined values.
Can anyone please help me out? I am just not much experienced with Javascript API.
Here is my AJAX code:
var tableAttorney = $('#table_affliate_attorney').DataTable({
destroy: true,
searching: true,
bLengthChange: false,
scrollX: true,
scrollY: 440,
autoWidth: false,
"language": {
"emptyTable": "We are sorry but there are no Affiliate Attorneys within a 150 mile radius of your requested search"
},
ajax: {
type: 'get',
url: "/wp-admin/admin-ajax.php",
dataType: 'json',
cache: false,
data: {
'action': 'get_attorney_ajax',
'center_lat': center_lat,
'center_long': center_long,
'state': state,
'city': city,
'zip': zip
}
},
columns: [
{"data": "title"},
{"data": "city"},
{"data": "state"},
{"data": "zip"},
{"data": "distance"},
{
"data": "phone",
className: 'datatablePhone',
render: function (data) {
return '' + data + '';
}
},
{
"data": "email",
className: 'px190EM',
render: function (data) {
return '' + data + '';
}
},
{
className: 'js-practice-area',
"data": "practice_area"
},
{
"targets": -1,
"data": 'email',
render: function (data) {
return "<a class='contact-lawyer' href='#' data-toggle='modal' data-target='#exampleModal' data-whatever='#mdo' data-email='"+data+"'>Contact</a>";
}
},
],
columnDefs: [
{"width": "150px", "targets": [0]},
{"width": "130px", "targets": [5]}
],
So I am trying to fetch data from columns->data that has value practice_area.
Here is the fiddle link where I have hosted my whole JS code: https://jsfiddle.net/fareeboy/apor08jn/1/
[1]: https://i.stack.imgur.com/4EOZS.png

Datatable columndefs not being hit

I have been trying to render my json in datatable. The json format i have been working with is as follows:
{
message: "",
data: {
count: "",
result: [
{
parameter1: "",
parameter2: "",
parameter3: "",
},
{
parameter1: "",
parameter2: "",
parameter3: "",
},
]
}
}
Datatable Code is as follow
$('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: "https://c22c6e75-a9b9-4762-8f5d-b25137536fa6.mock.pstmn.io/iprSearchData",
},
"columnDefs": [
{
"targets": [0],
"data": function (row, type, val, meta) {
// not hitting
console.log(row);
console.log(type);
console.log(val);
console.log(meta);
},
"render": function (data, type, row) {
console.log(data);
console.log(row);
return data;
},
},
// {targets: [0], visible: true},
// {targets: '_all', visible: false}
]
});
I read the documentation and I assume the data(JSON) format is creating problems for me in rendering or is it some other issue?
I want to render my parameters in reult array of the JSON to be displayed in a single column.
Thanks in advance.
The JSON format was the issue. Use datasrc in ajax for appropriate data from the returned ajax.

datatable warning 4 - Requested unknown parameter '0' for row 0, column 0

I am working on datatable and facing this error :
DataTables warning: table id=table - Requested unknown parameter '0'
for row 0, column 0.
I have studied this link and it says that my table column defines in HTML doesn't match with the columns received from server. BUT in my case both are same.
Here is my HTML code :
<table id="table" class="display responsive nowrap" cellspacing="0" width="100%">
<thead style="background-color:#303641;">
<tr>
<th>aNumber</th>
<th>bNumber</th>
<th>cellID</th>
<th>dateTime</th>
<th>duration</th>
<th>imei</th>
<th>imsi</th>
<th>operatorId</th>
<th>mscId</th>
<th>fileId</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Datatable javascript code :
var dataTable = $('#table').DataTable({
"processing": true,
"serverSide": true,
"bFilter": false,
"iDisplayLength": configData,
dom: 'Bfrtip',
buttons: ['colvis', 'print', 'csv', 'excel', 'pdf'],
searching: false,
language: {
buttons: {
colvis: 'Show/Hide Columns'
}
},
"ajax": {
url: "getAdvanceCallAnalysisData.json",
data: function(d) {
return $.extend({}, d, {
"offset": 0,
"newRequest": newReq,
"totalRecords": total,
"lookInCol": "aNumber",
"lookInVal": "43543543",
"fromDate": from_date,
"toDate": to_date,
"callingCellId": "",
"CalledCellId": "",
"cdrType": "",
"smsType": "",
"durationFilter": "",
"selectColumns": "",
"sortCol": "",
"sortType": "",
});
},
type: "POST",
error: function() {
alert("error");
},
complete: function(data) {
total = data.responseJSON.recordsTotal;
newReq = 0;
test(total, newReq);
$("#loading_image").hide();
$(".show_datatable").show();
},
"aoColumns": [{
"mData": "aNumber"
}, {
"mData": "bNumber"
}, {
"mData": "cellID"
}, {
"mData": "dateTime"
}, {
"mData": "duration"
}, {
"mData": "imei"
}, {
"mData": "imsi"
}, {
"mData": "operatorId"
}, {
"mData": "mscId"
}, {
"mData": "fileId"
}]
}
});
you can see that my columns name and numbers match with the columns define in ajax response.
I have done same thing for another table and it was working fine but it shows error here. don't know why !!
json response : (It returns 15 records, I posted only two just to make it short)
{"msg":null,"code":null,"status":null,"data":[{"aNumber":"343","bNumber":"3434","cellID":"410-01-831-14770","dateTime":"2017-08-23 17:27:54.0","duration":419,"imei":"22380831696837","imsi":"35340311428389","operatorId":4,"mscId":"5","fileId":"4"},{"aNumber":"3434","bNumber":"5656","cellID":"410-07-1314-28271","dateTime":"2017-08-23 22:02:15.0","duration":785,"imei":"49776303943255","imsi":"35722667519554","operatorId":1,"mscId":"2","fileId":"5"}],"draw":1,"limit":1000,"recordsFiltered":12,"recordsTotal":12}
The most funny part is it shows the correct records and pagination even it display correct rows (with empty data) in datatable. This ajax call returns 15 records. Please see the image below :
Any idea, what is wrong here ?

jQuery Datatables.net - refresh table - getting null sAjaxSource

I have the following function which should update a datatable in my ASP.NET site master page:
function refreshTable(oTable) {
var table = $(oTable).dataTable();
var oSettings = table.fnSettings();
//Retrieve the new data with $.getJSON. You could use it ajax too
$.getJSON(oSettings.sAjaxSource, null, function (json) {
table.fnClearTable(this);
for (var i = 0; i < json.aaData.length; i++) {
table.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
table.fnDraw();
});
}
This function is then called to refresh a table if an attachment is added to the site - this is the datatable settings that it should refresh.
var DeleteClicked = false;
var oTable;
$(document).ready(function () {
oTable = $('#infoTable').dataTable({
"aaSorting": [[6, "desc"]],
"bProcessing": true,
"sAjaxSource": '/Web/Handlers/infoTableHandler.ashx',
"aoColumns": [
{ "mData": "ID", "bVisible": false },
{ "mData": "Type" },
{ "mData": "Received" },
{
"mData": "Action", "sWidth": "100px", "mRender": function (data, type, row) {
var id = row.ID;
return "<input type=button id=" + id + " onclick='DeleteFile(" + id + ")' class=buttonBlue value=Delete />";
},
},
{ "mData": "IsImage", "bVisible": false }
],
"bDeferRender": true,
});
However - if I open Developer Tools in Chrome I get an error message saying sAjaxSource is null so i cannot then get the value from it - so oSettings is null and then I cannot get access to the sAjaxSource - anyone see anything wrong here?
you're basically reinitializing your dataTable in the first row of refreshTable. Try instead:
function refreshTable() {
var oSettings = oTable.fnSettings();
...
}
and refer directly to the global oTable instead of your local table variable

Using sAjaxSource works, but setting the aaData myseld does not

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

Categories

Resources