I'm trying to initialise a datatable using an object array located in the DOM
I have simple datatable initialisation code:
$(document).ready(function () {
$('#ManageSubReps').DataTable({
data: GetSRData(),
columns: [
{ "data": "username" },
{ "data": "AspNetUserRoleName" },
{ "data": "Name" },
{ "data": "Address" },
{ "data": "City" },
{ "data": "State" },
{ "data": "Zip" },
{ "data": "EmailAddress" },
{ "data": "HomePhone" },
{ "data": "CellPhone" },
{ "data": "New_Rep" },
{ "data": "Stand_By" },
{ "data": "DateApproved" },
{ "data": "AspNetUserID" }
]
});
});
My GetSRData function looks like this:
function GetSRData() {
return #Html.Raw(Model.JsonData)
}
My server side code looks like this:
public ActionResult ManagerSubReps(){
var model = new ManageSubRepsViewModel();
model.JsonData = JsonConvert.SerializeObject(new {data = _iManageSubRepsManager.GetSubRepsAsync(Session["CID"])});
return View(model);
}
A snipped of my data looks like this:
{"data":[{"username":"01001MC","MASTER":null,"Name":"A name","Address":"105 Address Dr.","City":"Agawam","State":"MA","Zip":"89898","EmailAddress":"blerb#yahoo.com","HomePhone":"","CellPhone":"8767878767","New_Rep":"False","Stand_By":"False","DateApproved":null,"AspNetUserID":null,"AspNetUserRoleName":null},{"username":"01002RG","MASTER":"False","Name":"Blooby palooby","Address":"7 Eaton drive, gumbie#Gmail.Com","City":"Amherst","State":"MA","Zip":"35656","EmailAddress":"chumpy#GMAIL.COM","HomePhone":"","CellPhone":"8986786654","New_Rep":"False","Stand_By":"False","DateApproved":null,"AspNetUserID":null,"AspNetUserRoleName":null}]}
HTML:
<table id="ManageSubReps" class="compact display">
<thead>
<tr>
<th>Username</th>
<th>Role</th>
<th class="dt-left">Name</th>
<th class="dt-left">Address</th>
<th class="dt-left">City</th>
<th>State</th>
<th>Zip</th>
<th class="dt-left">Email</th>
<th>Home Phone</th>
<th>Cell Phone</th>
<th>New Rep</th>
<th>Stand By</th>
<th>Approved Date</th>
<th></th>
</tr>
</thead>
</table>
When I return my data and try to initiliase the datatable, two things can happen:
If I remove the "data" part of the Json object then datatales will render the datatables but will not have any data in
If I leave the "data" part of the Json object then datatables will give me the error: 'Request unknown parameter '0' for row 0, column 0'. Which basically means that it cannot distinguish the data and form the datatable with the data.
I have checked the column data and it matches perfectly fine. I cannot figure out what the issue is.
Can anyone help?
EDIT: I know the issue has something to do with the data being a string, as I call HTML.Raw() on it. However, Im unsure of how to pass the data from the model without this
try ajax instead of data & fully qualified url(controller/api method) for getting ajax data:
$(document).ready(function() {
$('#ManageSubReps').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "ManagerSubReps",
columns: [
{ "data": "username" },
{ "data": "AspNetUserRoleName" },
{ "data": "Name" },
{ "data": "Address" },
{ "data": "City" },
{ "data": "State" },
{ "data": "Zip" },
{ "data": "EmailAddress" },
{ "data": "HomePhone" },
{ "data": "CellPhone" },
{ "data": "New_Rep" },
{ "data": "Stand_By" },
{ "data": "DateApproved" },
{ "data": "AspNetUserID" }
]
} );
} );
refer https://datatables.net/examples/server_side/object_data.html for more details.
Related
I have a dataTables table which its data is loaded by ajax call. Each row has 5 columns. The configuration is as follow:
<table id="table" class="table table-bordered table-hover" style="width: 100%">
<thead>
<tr>
<th>#Html.DisplayNameFor(model => model.FirstName)</th>
<th>#Html.DisplayNameFor(model => model.LastName)</th>
<th>#Html.DisplayNameFor(model => model.PersonnelId)</th>
<th>#Html.DisplayNameFor(model => model.NationalId)</th>
<th>#Html.DisplayNameFor(model => model.Companies)</th>
<th>Operations</th>
</tr>
</thead>
</table>
for initialization i use:
var table = $('.table').DataTable({
"proccessing": true,
"serverSide": true,
"ajax": {
url: "server_api.php",
type: 'POST'
},
"columns": [
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "PersonnelId" },
{ "data": "NationalId" },
{ "data": "Companies" }
]
});
Considering each row has an Id, how can i add Delete / Edit for each row in the operations column?
I solved the problem. To add data to an additional column you need to
add a column when initializing and
fill the column cell in the rowCallback function.
The code is:
var table = $('.table')
.DataTable({
"proccessing": true,
"serverSide": true,
"ajax": {
url: "server_api.php",
type: 'POST'
},
"columns": [
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "PersonnelId" },
{ "data": "NationalId" },
{ "data": "Companies" },
{ "render" : function() {return ""; }
],
"rowCallback": function (row, data) {
var additionalColIdx = 5; // Index of new column
$(`td:eq({additionalColIdx})`, row).html("Edit" + " / " +
"Delete");
}
});
I got a html table:
<table id="dattable" class="table table-striped table-bordered hover" cellspacing="0" >
<thead>
<tr>
<th>Name</th>
<th>Industry</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
and it is populated by JSON data. I want to use the render function to make items in the name column have a HTML link using the id field but it is not working.
var data2 =[
{
"id": "0",
"name": "Jack Spicer",
"industry__name": "System Architect",
"cost": "$3,120",
},
{
"id":"1",
"name": "Sean Spice",
"industry__name": "Motormouth",
"cost": "-$5,300",
}
];
$(document).ready(function() {
var table = $('#dattable').DataTable( {
data: data,
columns: [
{ data: 'name', "render": ""+[, ].name+""}, //render function
{ data: 'industry__name' },
{ data: 'cost' }
],
} );
} );
Based on your code, I think you need to change the definition of the column that generates the custom text you want. Also, I modified the call to render to use the function version.
var data2 = [{
"id": "0",
"name": "Jack Spicer",
"industry__name": "System Architect",
"cost": "$3,120",
}, {
"id": "1",
"name": "Sean Spice",
"industry__name": "Motormouth",
"cost": "-$5,300",
}];
$(document).ready(function() {
var table = $('#dattable').DataTable({
data: data2,
columns: [{
'data': null,
'render': function(data, type, row, meta) {
return '<a href=' + data.id + '>' + data.name + '</a>';
}
}, {
data: 'industry__name'
}, {
data: 'cost'
}]
});
});
You can take a lot at this as well, to see the changes I applied: https://jsfiddle.net/dr3hcd9j/
Live error example: http://live.datatables.net/virobeci/1/edit?html,css,js,output
I have a JavaScript object similar to this:
{
"rows": [
{
"doc": {
"CustomerName": "abc",
"key": "value",
"keyabc": "value"
}
},
{
"doc": {
"CustomerName": "abc",
"key": "value",
"keyabc": "value"
}
}
]
}
I've been trying for a long time to get DataTables to initialize using JavaScript datasource as mentioned here:
https://datatables.net/examples/data_sources/js_array.html
This is what I'm doing:
var table = $('#customersTable').DataTable( {
data: view,
columns: [
{ "rows" : 'doc.CustomerName' },
{ "rows" : 'doc.CustomerName' },
{ "rows" : 'doc.CustomerName' },
{ "rows" : 'doc.CustomerName' },
{ "rows" : 'doc.CustomerName' },
{ "rows" : 'doc.CustomerName' }
]
});
I get no errors, just 'No data available in table'
Table is defined like this:
<table id="customersTable" class="table table-striped table-bordered" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Number</th>
<th>Login</th>
<th>Party</th>
<th>Sales-Id</th>
<th>Sales-Party</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Number</th>
<th>Login</th>
<th>Party</th>
<th>Sales-Id</th>
<th>Sales-Party</th>
</tr>
</tfoot>
</table>
Live example: http://live.datatables.net/virobeci/1/edit?html,css,js,output
Edit -> PLEASE NOTE:
I can't change the format of the data source other than running a for loop and making a new array to match the sample data source. I wanna know if its possible to initialize the table with this type of data source
You haven't form your data properly:
var view = {
"rows": [
{
"CustomerName": "abc",
"key": "value",
"keyabc": "value"
},
{
"CustomerName": "abc",
"key": "value",
"keyabc": "value"
},
{
"CustomerName": "abc",
"key": "value",
"keyabc": "value"
}
]
};
And you have to assign the right array as data.row (although in your case you could simplify your structure a bit removing one level).
Note that you will have to add the data to the 'data' property of 'columns':
var table = $('#customersTable').DataTable( {
processing: true,
data: view.rows,
columns : [
{ data : 'CustomerName' },
{ data : 'CustomerName' },
{ data : 'CustomerName' },
{ data : 'CustomerName' },
{ data : 'CustomerName' },
{ data : 'CustomerName' }
]
});
you have to mention column name in your "columns" config and your data can be flattened.
http://live.datatables.net/poganaso/2/edit
you can try this,sample code is here:http://live.datatables.net/virobeci/2/edit?html,css,js,output
Suppose I have the following json to display in my DataTable:
// JSON structure for each row in this example:
// {
// "engine": {value},
// "browser": {value},
// "platform": {value},
// "version": {value},
// "grade": {value}
// }
$('#example').dataTable( {
"ajaxSource": "sources/objects.txt",
"columns": [
{ "data": "engine" },
{ "data": "browser" },
{ "data": "platform" },
{ "data": "version" },
{ "data": "grade" }
]
} );
What I want is, Add an Index Column to this data table for number the row.
Something like this :
"columns": [
{"data" : "Index"}, <------- this should number my rows
{ "data": "engine" },
{ "data": "browser" },
{ "data": "platform" },
{ "data": "version" },
{ "data": "grade" }
]
Note: I don't have any Index as data passed in my Json(Although I can do that, is there any better solution to handle this in my Javascript itself? )
Help appreciated..!
Try this.
"render": function ( data, type, full, meta ) {
return meta.row + 1;
} },
The concept is that you have to create the initial "Index" values either in javascript or in the server. The values can be zero or just empty strings or whatever (there is no need to calculate a counter or something). For example you can create an index column in javascript after you have received the data:
for (var i=0; i<data.length; i++){
data[i].index = 0;
}
So now that you have the index column in your data you declare it as the first column of your table:
$('#example').dataTable( {
.....
"columns": [
{ "data": "index" },
{ "data": "engine" },
{ "data": "browser" },
{ "data": "platform" },
{ "data": "version" },
{ "data": "grade" }
]
} );
Now the index values are all 0. To create the real index values that will be shown in the table you need to add an event handler that listens to the ordering and searching of the table. On these events the real index values will be calculated as described in the
datatables example:
datatable_object.on( 'order.dt search.dt', function () {
datatable_object.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
When the table is searched or ordered (ordering is done by default when the table is created - see default value of the order option), the innerHtml of the "Index" cells will be calculated based on the index of the row.
Just add the code below to your datatables
{ 'data': 'id', defaultContent: '' },
"columnDefs": [ ////define column 1 , make searchable false
{
"searchable": false,
"orderable": false,
"targets": 0
},
Below is the updated code:
var table=$('#example').dataTable( {
"ajaxSource": "sources/objects.txt",
"columns": [
{ 'data': 'id', defaultContent: '' },
{ "data": "engine" },
{ "data": "browser" },
{ "data": "platform" },
{ "data": "version" },
{ "data": "grade" },
"columnDefs": [ ////define column 1
{
"searchable": false,
"orderable": false,
"targets": 0
},
]
});
And the following line will add number to your id(index) column:
if (t.data().length != 0) {
t.on('order.dt search.dt', function () {
t.column(0, { search: 'applied', order: 'applied' }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1;
t.cell(cell).invalidate('dom');
});
}).draw();
Live example: http://live.datatables.net/woboviqi/2/edit
Need to use DT_RowIndex for indexing rows. Like this - ## Heading ##
"columns": [
{ "data": 'DT_RowIndex'}, // row index
{ "data": "engine" },
{ "data": "browser" },
{ "data": "platform" },
{ "data": "version" },
{ "data": "grade" }
]
You can use unshift()
"columns": [
{ "data": "engine" },
{ "data": "browser" },
{ "data": "platform" },
{ "data": "version" },
{ "data": "grade" }
].unshift({"data" : "Index"})
Or by using an temp array
var cols = [{
"data": "engine"
}, {
"data": "browser"
}, {
"data": "platform"
}, {
"data": "version"
}, {
"data": "grade"
}];
cols.unshift({
"data": "Index"
})
....
"columns": cols
Have a look on this URL: Data table Index column
It might help you.
Here is my code you can refer to:
My DataTable is complete custom.
I'm fetching data from the database using Ajax and CodeIgniter.
HTML
<table width="100%" class="table table-striped table-hover" id="table_id_dataTable">
<thead>
<tr>
<th>Sr No</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Sr No</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
JS Script
var temp_table = $('#table_id_of_dataTable').DataTable({
"language": {
"zeroRecords": "No records found."
},
"ajax": {
"type": "POST",
"url": "<?php echo base_url('Controller/method'); ?>"
},
"responsive": true,
"columnDefs": [
{
"searchable": false,
"orderable": false,
"targets": 0
}
],
"order": [
[1, 'asc']
],
"columns": [
{ "data": null }, // <-- This is will your index column
{ "data": "column_2_element_name_given_in_controller" },
{ "data": "column_3_element_name_given_in_controller" },
{ "data": "column_4_element_name_given_in_controller" },
{ "data": "column_5_element_name_given_in_controller" }
]
});
// Here we create the index column in jquery datatable
temp_table.on('order.dt search.dt', function() {
temp_nuggets_table.column(0, {
search: 'applied',
order: 'applied'
}).nodes().each(function(cell, i) {
cell.innerHTML = i + 1;
});
}).draw();
Hope it helps!
That is simple... This work for me.
Cell: function ( data, type, full, counter ) {
return data.index + 1
}
enter link description here
Try this:
var table=$('#example').dataTable( {
"ajaxSource": "sources/objects.txt",
"columns": [
{
"data": null, "render": function (data, type, full, meta) {
return meta.row + 1;
}
},
{ "data": "engine" },
{ "data": "browser" },
{ "data": "platform" },
{ "data": "version" },
{ "data": "grade" }
});
table.on('order.dt search.dt', function () {
table.column(0, { search: 'applied', order: 'applied' }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1;
});
}).draw();
enter link description here
Try this:
var table=$('#example').dataTable( {
"ajaxSource": "sources/objects.txt",
"columns": [
{
"data": null, "render": function (data, type, full, meta) {
return meta.row + 1;
}
},
{ "data": "engine" },
{ "data": "browser" },
{ "data": "platform" },
{ "data": "version" },
{ "data": "grade" }
});
I'm trying to fill JQuery Datatable with data via ajax:
HTML
<table id="table-productMaterials">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Quantity</th>
<th>Status</th>
</tr>
</thead>
</table>
Javascript
$(document).ready(function () {
var options = {
"processing": true,
"ajax": {
"url": "ProductMaterials.ashx?action=get",
"type": "POST",
"data": {
"productId": $('#product_id').val()
},
"columns": [
{ "data": "Id" },
{ "data": "MaterialName" },
{ "data": "Quantity" },
{ "data": "Status" }
]
},
};
table = $('#table-productMaterials').DataTable(options);
});
Generic handler output:
{"data": [{"Id":1,"Quantity":15.00,"Status":"1","MaterialName":"Iron","ProductName":"French onion soup"},{"Id":3,"Quantity":14.00,"Status":"1","MaterialName":"Nails","ProductName":"French onion soup"}]}
error message when reloading data:
DataTables warning: table id=table-productMaterials - Requested unknown parameter '0' for row 0. For more information about this error, please see http://datatables.net/tn/4
I refered to this page and read an example but can't seem to get this resolved. What I'm making wrong?
You have to place the columns property outside of the ajax property like this:
$(document).ready(function () {
var options = {
"processing": true,
"ajax": {
"url": "ProductMaterials.ashx?action=get",
"type": "POST",
"data": {
"productId": $('#product_id').val()
},
},
"columns": [
{ "data": "Id" },
{ "data": "MaterialName" },
{ "data": "Quantity" },
{ "data": "Status" }
]
};
table = $('#table-productMaterials').DataTable(options);
});
Then it will work.