Formatting server side jQuery Datatable - javascript

I am trying to format the front end look of my jQuery DataTable
I currently have it looking like this https://imgur.com/a/PPgL48Y
I need the repeating items in each row to be remove for example in the first row there are 2 Owner 1's. I only want to display a single Owner 1 in that row.
The other issue is in row 2, Url1 is followed by a comma then Url 2 but i want
Url1
Url2
In the row, so removing the comma and adding a new line in that col
My data is being collected via server side processing
My current jQuery code
<script type="text/javascript" >
$('#result').DataTable({
"serverSide":true,
"filter": false,
"orderMulti": false,
"ajax": "DetailedSearch?handler=ServerSideDataTable",
"columns":[
{"data": "location",
"render": function(data,type,row){
return row.location;
}
},
{"data": "contactAndRole",
"render": function(data,type,row){
return data.key + " - " + data.value;
}},
{"data": "server", "sortable": "false"},
{"data": "urls",
"render": function(data,type,row){
return row.urls + '<br>';
}
}
],
rowGroup:{
dataSrc:'appName'
}
});
</script>
Can i add some html elements? like a br after each url, or can the table be constructed with pure html then passed onto data tables to output?
I've looked into the HTML templates, and standalone documentation on the data tables website but nothing seems to be helpful.

The commas for the url's array are because of the default way arrays are processed to strings to be printed into the html in the dom
You could join() them yourself using a <br> separator instead
return row.urls.join('<br/>')

Related

How can I access array element value in json

I'm not able to access _sValues in my html page, however i can able to console.log the interested _sValues array element in console.
JSON
[
{
"_this":{
"_isEvent":false,
"_sNames":[
"name",
"tag",
"notes",
"input",
"type",
"action"
],
"_sValues":[
"Testing01",
"#13",
"1504013826",
"No details",
"cType",
"NA"
],
"_cName":"namesList",
"_dName":"TEST",
"_id":"12345",
}
}
]
HTML
<th class="col-md-5 col-xs-5" data-field="_this._sValues[1]" data-sortable="true">S-VALUES</th>
I would like to see #13 displayed on the page instead i don't see any values or console error. However i can display all values by doing _this.sValues
SCRIPT
var data;
$(function () {
$.getJSON("http://localhost:8080/services/webapi/getAllData", function(json){
data = json;
$('#table').bootstrapTable({
data: data
});
});
});
DEV TOOL
data[0]._this._sValues[1]
"#13"
In your case,
i assume you only have one row.
$(".col-md-5").attr("data-field",data[0]._this._sValues[1]);
It will inject the data to html.
If you have multi row, you can use for loop.
I believe you have a silent error. It has to do with the trailing comma in your data object.
"_id":"12345",
// should be
"_id":"12345"
That's all I noticed. I Courbet wrong but I know trailing commas mess with some browsers.

DataTables - how to render data with custom tag

This is how I use my custom tag in JSP
<utility:displayStatus value="${consumerForm.status }" />
When it comes to DataTables, I try to render the column like this :
"columnDefs": [
{
"targets": [ 0, 1 ],
"render" : function ( data, type, row ) {
var renderer = '';
renderer += '' + data + '';
return renderer;
}
},
{
"targets": 5,
"searchable": false,
"orderable": false,
"type" : "html",
"render" : function ( data, type, row ) {
var renderer = '<utility:displayStatus value="'+ data+'" />';
console.log(renderer)
return renderer;
}
},
I can get the html link display correctly in the datatables, but
'<utility:displayStatus value="'+ data+'" />'
cannot be rendered.
I tried with other html tag like label, span and button....and the result is correct.
Is it anyway to let the datatables render the custom tag correctly? Or Datatables is not support for custom tag such as JSTL ?
Thanks.
Browser want allowed you to display custom tags.
You can put your data in html tag's attribute like .
You can show/hide or customize your html tag in JS according to your data. Even you can access data-DepartmentCode further after rendering.
Cheers......

Load local array as Ajax file to improve performance

I am using DataTables to create a table, but it is loading awfully slow. I have approx. 9000 records that need to be processed from an SQL server (php is not an option). I am using XML and Spring MVC. I am using an XML and Java to gather the data and put it into a HashSet (i have tried lists also, neither seem faster than the other).
Once I get into JS I am using a for loop to populate my arrays, then I am using that as the "data" for the data tables. My understanding is that using serverSide and "ajax" (in place of data) will speed things up significantly so I was wondering if there was a way to take my arrays and use them as AJAX.
Thanks.
Current code:
var InternationalSet = [];
var storeIndex = 0;
<c:forEach items="${InternationalList}" var="entry">
InternationalSet[storeIndex]= ['', "${entry.getStoreId()}","${entry.getOrderPhone()}","${entry.getAddress1()}","${entry.getCity()}","${entry.getState()}", "${entry.getZip()}", "${entry.getMgrName()}",
"${entry.getFranchiseeName()}", "${entry.getOrglvl6Descr()}","${entry.getCommDescr()}", "${entry.getOrglvl8Name()}", "${entry.getLatitude()}", "${entry.getLongitude()}"];
storeIndex++;
</c:forEach>
$('#dataTable').html( '<table cellpadding="0" cellspacing="0" border="0" style="width: 99%; color:black" class="display compact" id="tableOne"></table>' );
var table = $('#tableOne').DataTable( {
"dom": '<l<t>ip>',
"deferRender": true,
"lengthChange": false,
"data": InternationalSet,
"pageLength": 10,
"orderMulti": false,
"columns": [.....
This is not a complete answer, but a quick improvement is to populate your list as a single statement instead of 9000.
var InternationalSet = [
<c:forEach items="${InternationalList}" var="e" varStatus="status">
[ '',
"${e.getStoreId()}",
"${e.getOrderPhone()}",
"${e.getAddress1()}",
"${e.getCity()}",
"${e.getState()}",
"${e.getZip()}",
"${e.getMgrName()}",
"${e.getFranchiseeName()}",
"${e.getOrglvl6Descr()}",
"${e.getCommDescr()}",
"${e.getOrglvl8Name()}",
"${e.getLatitude()}",
"${e.getLongitude()}"
] <c:if test="${!status.last}">,</c:if>
</c:forEach>
];
You can remove some of the new lines from the above to compactify it a little. Minor changes to the script also builds a single JSON object which you can return in an AJAX response to populate the table.
{
"data": [
<c:forEach items="${InternationalList}" var="e" varStatus="status">
....
</c:forEach>
]
}
If you are returning the data in sections from the server, your response would be changed to
{
"draw": ${param.draw},
"recordsTotal": ${yourTotal},
"recordsFiltered": ${yourFiltered},
"data": [
<c:forEach items="${InternationalList}" var="e" varStatus="status"
begin="${param.start}" end="${param.start + param.length}" >
....
</c:forEach>
]
}
(You will have to add some range/value checking on the param values)

Datatables TypeError: c is undefined

I try to use jQuery DataTables but I get the error
TypeError: c is undefined
I don't know what is wrong with my code as I can see the JSON correctly retrieve and is in the correct format too but I don't know what is wrong with it that I get the above error.
My JSON :
{"Data":[{"LOGIN":10184},{"LOGIN":10214},{"LOGIN":10180},{"LOGIN":10187},{"LOGIN":10179},{"LOGIN":10280},{"LOGIN":201},{"LOGIN":10238},{"LOGIN":10296},{"LOGIN":10312}]}
and my DataTables code:
$(document).ready(function() {
$('#tablename').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"type": "POST",
"url": "https://test.com/api/db/select",
"data": function ( json ) { return JSON.stringify( { "Sql": 12 } );},
"contentType": "application/json; charset=utf-8",
"dataType": "json",
"processData": true,
beforeSend : function(xhr){
var access_token = sessionStorage.getItem('access_token');
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
}
},
"dataSrc": "Data",
"columns": [
{ "data": "LOGIN" }
]
} );
} );
Check whether you have added
<thead></thead>
<tbody></tbody>
I've resolved this problem by adding those.
So basically the structure must be like:
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Sometime, This type issue arrives by fixing mismatched / unequal columns with HTML and datatables columns.
"columns": [
null,
null,
null,
{"orderable": false, "width":"2%"},
],
Above javascript defined 4 columns and HTML having 5 columns
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
<td>E</td>
</tr>
Hence you will have to fix / equal both side HTMl and Datatable configuration.
"columns": [
null,
null,
null,
null, //Added New
{"orderable": false, "width":"2%"},
],
dataSrc is a special dataTables ajax option, that should be included inside the ajax object :
"ajax": {
"dataSrc": "Data", //<--- place dataSrc here instead
"type": "POST",
...
}
You have placed it outside ajax, and by that dataTables have no idea what source to use (besides blindly trying the ajax response) or where LOGIN belongs.
in my case, i had to remove colspan attribute from a th inside thead and get rid of the error ;(
In my case, missing aaData in sever side return result.
//Javascript
$('#table').DataTable({
sAjaxSource: '/load',
aoColumns: [
...
],
});
//server side(in Rails)
render json: {'aaData'=>data}
In my case, I got the same error because I used the ajax.dataSrc( data ) function to manipulate the data. But after that i forgot to return the data.
"dataSrc": function ( json ) {
for ( var i=0, ien=json.data.length ; i<ien ; i++ ) {
//somethings...
}
return json.data;// I forgot this line, then i got the error "TypeError: c is undefined"
}
After a few minutes, I checked the documentation of the ajax.dataSrc function and I noticed that I did not have the return:
Returns: array. Array of data that DataTables is to use to draw the table
I hope you do not have the same distraction...
In my case th and td , count is not equal due do colspan, removed colspan and it worked.
In my case, my front-end: ajax: { dataSrc: "data" } was OK, but on server-side I returned object where first letter was Upper return Json(new { Data = model });
Another day, another solution - this time caused by a style sheet!
After spending hours reducing a gigantic web page to the raw charts code, I found that this error shows (for pie charts) when CSS rules for fonts in the stylesheet contain the calc function.
In our style sheet, this line of code:
html {
font-size: calc(12px + 5%);
}
...broke the chart. We needed this because our webfont wasn't resizing smoothly and needed a size slightly larger than 12px but smaller than 13px, and this trick forced a better resize.
Overwriting the style rule on the chart widget directly solved the issue:
CSS
html {
font-size: calc(12px + 5%);
}
.widget {
font-size: 12px /* Replace the above rule */;
}
JS
var GoogleChart1 = new google.visualization.PieChart(document.getElementById('Chart1'));
HTML
<div id="Chart1" class="widget"></div>
check followings
<td></td> -- check count
<th></th> -- check count
check <tbody> and <thead> - opening and closing
In my case the number of column in <thead> tag is different than the number of column in <tbody> tag.

How do I add an index column to Datatable?

I want to add a row number for each row in my data table. I am using plugin from http://datatables.net The page which tells how to add the index is http://datatables.net/release-datatables/examples/api/counter_column.html
... however I don't know how to actually implement it to make it work. I know extremely little about jquery / javascript which would help in this case. I don't know where to put this code to make it work (if it helps i am also using Ruby on Rails)
The initialization code is:
jQuery ->
$('#staffs').dataTable
sPaginationType: "full_numbers"
bJQueryUI: true
}
Here is an example from datatables.net site DataTables row numbers example
$(document).ready(function() {
$('#staffs').dataTable( {
sPaginationType: "full_numbers",
bJQueryUI: true,
"fnDrawCallback": function ( oSettings ) {
/* Need to redo the counters if filtered or sorted */
if ( oSettings.bSorted || oSettings.bFiltered )
{
for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
{
$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
}
}
},
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0 ] }
],
"aaSorting": [[ 1, 'asc' ]]
} );
} );
Regarding your SyntaxError: reserved word "function" on line 4 (in /home/ubuntu/ruby/scoreboard/app/assets/javascripts/staffs.js.coffee)' error
take a look at this rails, getting syntax error with coffee script
jquery is javascript. You need to add the code Daniel pasted between
<script language="javascript">
and
</script>
tags.
I am working with latest dataTable 1.10 and gem rails datatable and ajx
for
finding the DataTable row number(Serial Number)
def data
outer = []
records.each_with_index do |record, index|
outer << [
# comma separated list of the values for each cell of a table row
# example: record.attribute,
index + 1 + params[:start].to_i,
record.company_name,
record.id,
record.patients.count,
record.revenue_total
]
end
outer
end

Categories

Resources