Binding datatable with to JSON array from autocomplete - javascript

I am using an autocomplete field to get data from a server and display that in a datatable:
$("#firstname").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://myhost.com/webservices/test3.cfm",
data: request,
success: function (data) {
$('#results').dataTable({
"bProcessing": true,
"bJQueryUI": true,
"bLengthChange": true,
"bFilter": true,
"bAutoWidth": false,
"bRetrieve" : true,
"aaData": data ,
"aoColumns": [
{ "sTitle": "Name", "sName": "name" },
{ "sTitle": "Title", "sName": "title" },
{ "sTitle": "Organization", "sName": "organization" },
{ "sTitle": "Email", "sName": "email" },
{ "sTitle": "Status", "sName": "status" }
]
});
}
});
}
The data return from the ajax call is:
[["Steven, Grek", "President", "Sands Corp.", "steven#yahoo.com", "1"],["Steven, Grek", "Associate", "Alliance Ltd.", "steven#yahoo.com", "1"],["Steven, Grek", "President", "Forest Products Association", "steven#yahoo.com", "1"]]
I get the following errors:
DataTables warning (table id = 'results'): Requested unknown parameter '1' from the data source for row 0
DataTables warning (table id = 'results'): Requested unknown parameter '1' from the data source for row 9
Showing 1 to 10 of 2,147 entries
If I replace "aaData": data
with the response from in the data:
"aaData": [["Steven, Grek", "President", "Sands Corp.", "steven#yahoo.com", "1"],["Steven, Grek", "Associate", "Alliance Ltd.", "steven#yahoo.com", "1"],["Steven, Grek", "President", "Forest Products Association", "steven#yahoo.com", "1"]]
it works.
Any idea what I am doing wrong?

Figured it out with the help of a co-worker:
The typeof data coming from my ajax call is a string.
$("#firstname").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://myhost.com/webservices/test3.cfm",
data: request,
success: function (data) {
var obj = jQuery.parseJSON(data); <---- typeof data is a string
$('#results').dataTable({
"bProcessing": true,
"bJQueryUI": true,
"bLengthChange": true,
"bFilter": true,
"bAutoWidth": false,
"bRetrieve" : true,
"aaData": obj, <---- Use the parsed json object instead
"aoColumns": [
{ "sTitle": "Name", "sName": "name" },
{ "sTitle": "Title", "sName": "title" },
{ "sTitle": "Organization", "sName": "organization" },
{ "sTitle": "Email", "sName": "email" },
{ "sTitle": "Status", "sName": "status" }
]
});
}
});
},
});

Related

how To get a large data in Jquerydatatable

I am new in MVC application, I have handled the large data in Jquery datatable Server side script working fine when all data loaded(ex: Select the all Records in particular table).
If I make manual filter (ex: Select * from xxx where zzz=yyy) then I am not able to send parameters to controller action.
Please find the below script.
$(document).ready(function () {
debugger
var oTable = $('#PartUpdate').dataTable({
"bServerSide": true,
"sAjaxSource": "Test/AjaxHandler",
data: $.param({ 'b':'Mani'}),
"bProcessing": true,
buttons: [
'csv', 'excel', 'print'
],
"aoColumns": [
{
"sName": "ID",
"bSearchable": false,
"bSortable": false,
"fnRender": function (oObj) {
return 'View';
}
},
{ "sName": "UserName" },
{ "sName": "FullName" },
{ "sName": "EmailId" }
]
});
});

Push AJAX retrieved JSON into Datatables

I'm using the datatables plugin and it's working fine for me. However, I'm making multiple calls to populate multiple tables, when I know I could make one AJAX call and store the results in a variable and have each table function use that variable for its data, but I can't get it to work.
I'm using something like to to get the data I need.
var all_data;
$.ajax({
async : false,
url: 'all_data.php',
type: 'GET',
success: function(data) {
all_data = data;
console.log(all_data);
}
})
The idea is to pass all_data variable into my table function (I have several on this one page) without having to make multiple calls. Doing the following returns one column with the letter "a", which isn't right. The data that comes back is JSON coded. I've used the below code, but with the AJAX function as part of the table function:
$("#my_table").DataTable({
"data":all_data
,
"paging": true,
"sDom": '<"top">t<"bottom"><"clear">',
"pageLength": 50,
"order": [[ 4, "desc" ]],
"aoColumns": [
{ "bSortable": true, "width": "0%", "sClass": "lang_body_2", "sTitle": "","visible":false },
{ "bSortable": true, "searchable": false, "width": "10%", "sClass": "lang_body_2 table_names", "sTitle": "" },
{ "bSortable": true, "searchable": false,"width": "20%", "sClass": "lang_body_2", "sTitle": "Database","visible":false},
{ "bSortable": true, "searchable": false ,"width": "20%","sClass": "lang_body_2","sTitle": "National Average","visible":false },
{ "bSortable": true, "searchable": false ,"width": "50%","sClass": "lang_body_2 index_num table_index","sTitle": "" },
],
"columns": [
{ "searchable": true },
{ "searchable": false },
{ "searchable": false },
{ "searchable": false },
{ "searchable": false },
],
"search": {
"search": "gen"
},
"columns": [
{ "width": "20%" },
null,
null,
null,
{ "width": "80%" },
],
"initComplete": function(settings, json) {
colorIndex();}
});
});
What am I doing wrong here? I'm suspecting I have to prepare all_data somehow, but I'm not sure what that might be.
EDIT: If I console.log the data returned, this is what I get (cut off for brevity):
Object {draw: 0, recordsTotal: 484, recordsFiltered: 484, data: Array[484]}
data: Array[484]
[0 … 99]
0: Array[5]
0: "edu"1: "High School"2: "37.90"3: "49.70"4: "76"length: 5
Your code looks fine, the only thing you need to do is
Assign your datatable to a variable and then in your ajax resolve clear, add data and draw the table.
var all_data;
$.ajax({
async : false,
url: 'all_data.php',
type: 'GET',
success: function(data) {
all_data = data;
console.log(all_data);
table.clear().row.add(all_data).draw(); //clear, add data and draw
}
});
// Assign your datatable to a variable
var table = $("#my_table").DataTable({
"data":all_data
,
"paging": true,
"sDom": '<"top">t<"bottom"><"clear">',
"pageLength": 50,
"order": [[ 4, "desc" ]],
"aoColumns": [
{ "bSortable": true, "width": "0%", "sClass": "lang_body_2", "sTitle": "","visible":false },
{ "bSortable": true, "searchable": false, "width": "10%", "sClass": "lang_body_2 table_names", "sTitle": "" },
{ "bSortable": true, "searchable": false,"width": "20%", "sClass": "lang_body_2", "sTitle": "Database","visible":false},
{ "bSortable": true, "searchable": false ,"width": "20%","sClass": "lang_body_2","sTitle": "National Average","visible":false },
{ "bSortable": true, "searchable": false ,"width": "50%","sClass": "lang_body_2 index_num table_index","sTitle": "" },
],
"columns": [
{ "searchable": true },
{ "searchable": false },
{ "searchable": false },
{ "searchable": false },
{ "searchable": false },
],
"search": {
"search": "gen"
},
"columns": [
{ "width": "20%" },
null,
null,
null,
{ "width": "80%" },
],
"initComplete": function(settings, json) {
colorIndex();}
});
});

Bootstrap datepicker passing to c# ajax call

I am having difficulty passing a date to ajax call. The date is from a bootstrap datetimepicker. I do get the value javascript side by using:
var DateFrom = $("#dpDateFrom").data('datepicker').date;
I pass this date via ajax call from a datatable.
tblActivity = $('#tblActivity').dataTable({
"oLanguage": { "sEmptyTable": "No data to display" },
"bJQueryUI": false,
"bAutoWidth": false,
"sAjaxSource": '/api/activitylogapi/Activityt',
"aaData": mainJson.aaData,
"bProcessing": false,
"bServerSide": true,
"bSort": true,
"bFilter": false,
"bRetrieve": true,
"aoColumns": [
{ "sTitle": "Activity Type", "mDataProp": "Type", "sWidth": "10%" },
{ "sTitle": "Comments", "mDataProp": "Comments", "sWidth": "10%" },
{ "sTitle": "Company Name", "mDataProp": "CompanyName", "sWidth": "10%" },
{ "sTitle": "Contact", "mDataProp": "Contact", "sWidth": "10%" },
{ "sTitle": "User", "mDataProp": "UserFullName", "sClass": "truncate", "sWidth": "10%" },
{ "sTitle": "Created", "mDataProp": "DateS", "sClass": "text-right", "sWidth": "10%" },
],
"iDeferLoading": [mainJson.count, mainJson.count],
"aoColumnDefs": [{ "bSortable": false, "aTargets": [1,2,3,5] }],
"fnServerData": function (sSource, aoData, fnCallback, oSettings) {
aoData.push({ "name": "DateFrom", "value": DateFrom });
aoData.push({ "name": "DateTill", "value": DateTill });
doDataTablePostAjaxCalling(this, sSource, aoData, fnCallback, oSettings);
},
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
}
My ajax call is expecting a DateTimeOffset but can not get the date to pass through succesfully. Is there a way I must fomrat my javascript date
I resolved this by getting the value from datepicker with .val(). Then creating a date object in javascript then passing that to my controller.

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.

DataTables: search all columns when server-side

I'm using IgnitedDatatables (CodeIgniter library) for DataTables. The table gets generated without problems but if I search/filter it can only filter one column at a time. If I set "bServerSide" to false it works but then I lose the server-side functionality.
In the examples, this one is working:
http://datatables.net/release-datatables/examples/ajax/custom_data_property.html
while this isn't (server-side):
http://datatables.net/release-datatables/examples/data_sources/server_side.html
Is this not possible to achieve when running server-side?
This is my JSON response (shortened and with replaced data):
{"sEcho":0,"iTotalRecords":45438,"iTotalDisplayRecords":45438,"aaData":[["abc","12345","example#example.com","","","2010-01-27 22:31:10","Edit<\/a> Delete<\/a>"],["abc2"," test123","test#test.com","","","2008-06-15 22:09:33","Edit<\/a> Delete<\/a>"]],"sColumns":"fname,lname,email,phone,cellphone,created,edit"}
JavaScript code:
$("#members").dataTable( {
"bProcessing": true,
"bServerSide": true,
'sAjaxSource': '<?php echo base_url();?>members/listener',
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.ajax( {
"dataType": 'json',
"type": 'POST',
"url": sSource,
"data": aoData,
"success": fnCallback
} );
},
"bLengthChange": false,
"aaSorting": [[ 0, "asc" ]],
"iDisplayLength": 15,
"sPaginationType": "full_numbers",
"bAutoWidth": false,
"aoColumnDefs": [
{ "sName": "fname", "aTargets": [ 0 ] },
{ "sName": "lname", "aTargets": [ 1 ] },
{ "sName": "email", "aTargets": [ 2 ] },
{ "sName": "phone", "sWidth": "80px", "aTargets": [ 3 ] },
{ "sName": "cellphone", "sWidth": "100px", "aTargets": [ 4 ] },
{ "sName": "created", "sWidth": "120px", "aTargets": [ 5 ] },
{ "bSortable": false, "sName": "edit", "sWidth": "115px", "aTargets": [ 6 ] }
]
});
Thank you!
Well, the problem if you filter server side is that you are filtering through an SQL query and this is what is written on the example you posted;
Filtering
NOTE this does not match the built-in DataTables filtering which does it
word by word on any field. It's possible to do here, but concerned about efficiency
on very large tables, and MySQL's regex functionality is very limited
Basically you could do what you want to do (a regular expression match an all columns) but it's going to kill the performance server side.
What i usually do is provide a filter for each column, i need to filter.

Categories

Resources