Datatable render after AJAX call - javascript

I am trying to render a data table by making an AJAX call getting some data from controller and then writing data table. sData['id'] is just a number
Here is my code:
$.post('/admin/user_groups_data/' + sData['id']).done(function(data) {
$('#user_groups_table').dataTable({
"bProcessing": true,
"bDeferRender": true,
"sPaginationType": "full_numbers",
"aaData": data, // data here is a JSON object, shows on Firebug correct data and fields
"aoColumns": [
{ "mData": "id"},
{ "mData": "title" },
{ "mData": "category" },
]
});
});
Below is my HTML code
<table id="user_groups_table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Type</th>
</tr>
</thead>
</table>
It seems like the data table gets rendered first even before AJAX call is done so it gives me error
DataTables warning (table id = 'user_groups_table'): Requested unknown parameter 'id' from the data source for row 0
I have the .done at top but seems like it doesn't even respect that. Any help would be great. thx

Just added sAjaxSource to it and it works now, seems like the $.post had not completed yet when data table was being written, sAjaxSource retrieves the data and brings it back and then writes data table.
var oTable = $('#user_groups_table').dataTable({
"bDestroy": true,
"bProcessing": true,
"bDeferRender": true,
"sPaginationType": "full_numbers",
//"aaData": data,
"sAjaxSource": '/admin/user_groups_data/' + sData['id'],
"aoColumns": [
{ "mData": "group_id", "bVisible": false},
{ "mData": "title" },
{ "mData": "category" },
]
});

Related

DataTable shows zero rows even get the response

I have a datatable.I tried to load via ajax .The response contain data but it shows no data found.My code is given below
<table id="user_list_table">
<thead>
<tr>
<th>name</th>
<th>phone</th>
<th>email</th>
<th>address</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
My js contains
$(document).ready(function() {
var MY_AJAX_ACTION_URL = "/social/index.php?id=4&userform[action]=datatable&userform[controller]=User";
$('#user_list_table').dataTable({
"autoWidth": false,
"bPaginate": false,
"searching": false,
"ordering": true,
"oLanguage": {
"sZeroRecords": "No data Found",
"sProcessing": 'processing'
},
"bInfo": false,
"aoColumns": [
{'mData':'name','bSortable': true},
{'mData':'phone','bSortable': true},
{ 'mData':'email','bSortable': true },
{ 'mData':'address','bSortable': true}
],
"sAjaxDataProp": "",
"bProcessing": true,
"bServerSide": true,
"sAjaxSource":MY_AJAX_ACTION_URL
});
});
I got the following response
{"iTotalRecords":2,"iTotalDisplayRecords":{"data":[{"name":"xyz","phone":"678654454","email":"xyz#gmail.com","address":"ytruye"},{"name":"abc","phone":"678654454","email":"abc#gmail.com","address":"ytruye"}]}}
The server response is a little bit missed up. You have
{
"iTotalRecords": 2,
"iTotalDisplayRecords": {
"data": [
but iTotalDisplayRecords is supposed to be the number of filtered records (and iTotalRecords of course the total number of records). If you correct the response to
{
"iTotalRecords": 2,
"iTotalDisplayRecords": 2,
"data": [
{
and remove "sAjaxDataProp": "", then it works -> http://jsfiddle.net/2o6eLt2z/
So the problem is serverside, there is no possible way to correct the problem clientside since the JSON will never work with dataTables as a serverside source. You could use the serverscript in an ajax: { url: ...} and return the corrected JSON in the dataSrc callback, but it seems to me you want to use serverside processing.

DataTable Error - Cannot read property 'length' of undefined

I am trying to build my DataTable (1.10.5) using an ajax call to a service - http://www.datatables.net/examples/ajax/
Here is my Javascript:
$('#tableexample').DataTable({
"dom": 'C<"clear">lfrtip',
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "../../api/EventTypes/GetAll",
"aoColumnDefs": [
{
"aTargets": [0],
"mData": "Id"
},
{
"aTargets": [1],
"mData": "Name"
},
{
"aTargets": [2],
"mData": "Name"
},
{
"aTargets": [3],
"mData": "Name"
},
{
"aTargets": [4],
"mData": "Name"
}
]
});
Here is my HTML:
<table id="tableexample" class="table table-striped dataTable table-hover">
<thead>
<tr>
<th>Select</th>
<th>Event</th>
<th>Primary Category</th>
<th>Secondary Category</th>
<th>Workflow</th>
</tr>
</thead>
</table>
Here is my error:
Uncaught TypeError: Cannot read property 'length' of undefined
If I look i my jquery.dataTables.js - it says that my data is undefined...
var data = _fnAjaxDataSrc( settings, json );
Can anyone help me out with setting up my ajax call properly to dynamically build my table??
Thanks!
Finally found it!
I needed to make an ajax call and pass the data to "aaData":
$.ajax({
url: '/Portal/api/EventTypes/GetEventWorkflowDefinitions',
type: 'GET',
dataType: 'json',
success: function (data) {
assignToEventsColumns(data);
}
});
function assignToEventsColumns(data) {
var table = $('#tableexample').dataTable({
"dom": 'C<"clear">lfrtip',
"bAutoWidth": false,
"aaData": data,
"aaSorting": [],
"aoColumnDefs": [
{
"aTargets": [0],
"bSearchable": false,
"bSortable": false,
"bSort": false,
"mData": "EventTypeId",
"mRender": function (event) {
return '<input class="childCheck" type="checkbox" id="childCheckBoxes" value="' + event + '">';
}
},
{
"aTargets": [1],
"mData": "EventType"
}
Once I did this...the table build perfectly!

server side data loading from C# in jquery datatable

Hi i have successfully implemented jquery data table server side call,but i am unable to load data in html view
it just says processing
here is my Js code
$('#internetTable').dataTable({
'bProcessing': true,
'bServerSide': true,
'sAjaxSource': 'api/values/GetInternetSales'
"aoColumns": [
{ "mData": "Calls" },
{ "mData": "LevelOneOperators" },
{ "mData": "LevelTwoOperators" },
{ "mData": "Issueraised" },
{ "mData": "SalesDate" },
{ "mData": "AutomaticResponses" }
]
});
and this is html code
<table id="internetTable" class="table table-bordered table-hover">
<thead>
<tr>
<th >Date</th>
<th>Issue Raised</th>
<th>Level One Operators</th>
<th >Level Two Operators</th>
<th>Automatic Responses</th>
<th>Calls</th>
</tr>
</thead>
</table>
And the response am getting from server is
{"sEcho":"2","iTotalRecords":10,"iDisplayStart":1,"iDisplayEnd":1,"iDisplayLength":10,"iTotalDisplayRecords":100,"InternetDataList":[{"Calls":"320","LevelOneOperators":"1","LevelTwoOperators":"7","Issueraised":"1","SalesDate":"2010-11-25T00:00:00","AutomaticResponses":235}]}
Now,just want to ask that what modifications in JS code do i need to do to parse it in table,as i have searched alot but could'nt get any solution.
Got the answer i need to add following code in js:
$('#internetTable').dataTable({
'bProcessing': true,
'bServerSide': true,
"sServerMethod": "GET",
// to enable Pagination
"sPaginationType": "full_numbers",
'sAjaxSource': 'api/values/GetInternetSales',
"sAjaxDataProp": "InternetDataList",
"aoColumnDefs": [{
"mData": "InternetDataList"
}],
"aoColumns": [
{ "mData": "Calls" },
{ "mData": "LevelOneOperators" },
{ "mData": "LevelTwoOperators" },
{ "mData": "Issueraised" },
{ "mData": "AutomaticResponses" },
{ "mData": "SalesDate" }
]
});
As,here the sAjaxDataProp is your data name as in my case it is InternetDataList and default it is aadata

DataTables stuck on "Processing" when sorting

Below is the document ready function
$('#example').dataTable({
"bProcessing": true,
"bServerSide": true,
"aaSorting": [[2, "asc"]],
"sAjaxSource": "/userControl/GetUser.php",
"aoColumnDefs": [{
"aTargets": [0],
"mData": "download_link",
"mRender": function (data, type, full) {
return 'Detail<br/>Delete';
}
}],
"aoColumns": [
{ "mData": null },
{ "mData": "LoginId" },
{ "mData": "FirstName" },
{ "mData": "LastName" }
]
});
var oTable = $('#example').dataTable();
oTable.fnSort([1, 'asc']);
With the above code, the datatable was stuck on "Processing..." like the below screen shows, but if I remove the sorting, the data was shown correctly, but whenever the user request a column to be sort, the result was still the same, is there anything that I did wrong?
I removed "bServerSide": true, and the DataTables can sort and filter properly now
Your server-side implementation has to handle sorting via the iSortCol parameters, using fnSort is for client-side implementations and will not work for server-side
As #mainguy said in his comment, removing bServerSide will disable pagination and more than likely search
Look at the examples for asp.net on the site, as thats the lang you tagged, if you need more assistance, update your question with the asp.net source code
Please see if your server response has the same counter value for draw or sEcho property as sent by the client.
Example, request may contain draw: 11 or sEcho: 11 parameters, then, the server response must contain draw: "11" or sEcho: "11".

jquery datatables: adding extra column

Scenario
I am using datatables (#version 1.9.4) for the first time to display data to the user.
I succeed in retrieving the data via ajax and in binding them to the datatable.
Now I want to add extra columns to let the user process the records. For semplicity sake, the aim is to add a button with an onclick handler that retrieve the data of the 'clicked' record.
In my plan I would bind the json item corresponding to the 'clicked' record to the onclick handler.
Till now, if I add an additional TH for the action column to the DOM, an error occurs from datatables code:
Requested unknown parameter '5' from data source for row 0
Question
How to set custom columns? How to fill their content with HTML?
Here is my actual config.
HTML
<table id="tableCities">
<thead>
<tr>
<th>country</th>
<th>zip</th>
<th>city</th>
<th>district code</th>
<th>district description</th>
<th>actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
Javascript
$('#tableCities').dataTable({
"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bSort": true,
"bInfo": false,
"bAutoWidth": true
, "bJQueryUI": true
, "bProcessing": true
, "bServerSide": true
, "sAjaxSource": "../biz/GetCitiesByZip.asp?t=" + t
});
Sample Json result
{
"aaData":
[
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino"
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino"
]
],
"iTotalRecords": 2,
"iTotalDisplayRecords": 2,
"iDisplayStart": 0,
"iDisplayLength": 2
}
Edit
Daniel is right. The solution is to set up the custom column in the aoColumnDefs, specifying the mData and the mRender properties. In particular mRender lets to define custom html and javascript.
/* inside datatable initialization */
, "aoColumnDefs": [
{
"aTargets": [5],
"mData": null,
"mRender": function (data, type, full) {
return 'Process';
}
}
]
You can define your columns in a different way
like this
"aoColumns": [
null,
null,
null,
null,
null,
{ "mData": null }
]
or this
"aoColumnDefs":[
{
"aTargets":[5],
"mData": null
}
]
Here some docs Columns
Take a look at this DataTables AJAX source example - null data source for a column
Note that prior to DataTables 1.9.2 mData was called mDataProp. The name change reflects the flexibility of this property and is consistent with the naming of mRender. If 'mDataProp' is given, then it will still be used by DataTables, as it automatically maps the old name to the new if required.
Another solution/workaround could be adding that '5' parameter...
For example adding extra "" to each row
like this:
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino",
""
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino",
""
]
Just in case anyone using a newer version of DataTables (1.10+) is looking for an answer to this question, I followed the directions on this page:
https://datatables.net/examples/ajax/null_data_source.html
Posting this answer here, just to show that where the aoColumnDefs needs to be defined. I got help from this question it self, but I struggled for a while for where to put the aoColumnDefs. Further more also added the functionality for onclick event.
$(document).ready(function() {
var table = $('#userTable').DataTable( {
"sAjaxSource": "/MyApp/proctoring/user/getAll",
"sAjaxDataProp": "users",
"columns": [
{ "data": "username" },
{ "data": "name" },
{ "data": "surname" },
{ "data": "status" },
{ "data": "emailAddress" },
{ "data" : "userId" }
],
"aoColumnDefs": [
{
"aTargets": [5],
"mData": "userId",
"mRender": function (data, type, full) {
return '<button href="#"' + 'id="'+ data + '">Edit</button>';
}
}
]
} );
$('#userTable tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
console.log(data);
$('#userEditModal').modal('show');
});
} );

Categories

Resources