Datatables with Ajax - javascript

I'm new to dataTabels and I'm trying to get data from a json txt file (test1.txt). This is a part of it (only 4) but I have +5000:
[{"0":"22352442","ID":"22352442","1":"22126303","PARENT":"22126303","2":"2813340","TASK_ID":"2813340","3":"2667252","CHILD_ID":"2667252","9":"Shawne Walthall","LEAD":"Shawne Walthall","11":"RP ~217' cable- PL 8 YPSIL","DESCRIPTION":"RP ~217' cable- PL 8 YPSIL","12":"PD-SW-ANN","WORKLOCATION":"PD-SW-ANN","13":"IC","TASKTYPE":"IC","14":"HOLD","STATUS":"HOLD","15":"INFLD","C_STATUS":"INFLD","16":"Scheduled","CLASSIFICATION":"Scheduled","18":"RFW672917A11 INSTALL CABLE - 05-181","TASK_DESCRIPTION":"RFW672917A11 INSTALL CABLE - 05-181","19":"Overload","TYPE_OF_WORK":"Overload","20":"16-NOV-06","TS":"16-NOV-06","21":"24-JAN-11","TC":"24-JAN-11"},{"0":"27364695","ID":"27364695","1":"27364637","PARENT":"27364637","2":"11949147","TASK_ID":"11949147","3":"11949089","CHILD_ID":"11949089","11":"08-036 Design System Cable NF 52R Howard","DESCRIPTION":"08-036 Design System Cable NF 52R Howard","12":"PD-SE-TBY","WORKLOCATION":"PD-SE-TBY","13":"TC","TASKTYPE":"TC","14":"WAPPR","STATUS":"WAPPR","15":"INFLD","C_STATUS":"INFLD","16":"Scheduled","CLASSIFICATION":"Scheduled","18":"TEST CABLE","TASK_DESCRIPTION":"TEST CABLE"},{"0":"28728012","ID":"28728012","1":"28728001","PARENT":"28728001","2":"31575951","TASK_ID":"31575951","3":"31575940","CHILD_ID":"31575940","9":"Clifton Manus","LEAD":"Clifton Manus","11":"08-098, Design\/Construct System Cable","DESCRIPTION":"08-098, Design\/Construct System Cable","12":"PD-SE-TBY","WORKLOCATION":"PD-SE-TBY","13":"IC","TASKTYPE":"IC","14":"APPR","STATUS":"APPR","15":"INFLD","C_STATUS":"INFLD","16":"Scheduled","CLASSIFICATION":"Scheduled","18":"08-097, INSTALL CABLE","TASK_DESCRIPTION":"08-097, INSTALL CABLE","19":"Reliability","TYPE_OF_WORK":"Reliability","20":"12-AUG-08","TS":"12-AUG-08","21":"12-AUG-17","TC":"12-AUG-17"},{"0":"28728014","ID":"28728014","1":"28728001","PARENT":"28728001","2":"31575953","TASK_ID":"31575953","3":"31575940","CHILD_ID":"31575940","11":"08-098, Design\/Construct System Cable","DESCRIPTION":"08-098, Design\/Construct System Cable","12":"PD-SE-TBY","WORKLOCATION":"PD-SE-TBY","13":"TC","TASKTYPE":"TC","14":"WAPPR","STATUS":"WAPPR","15":"INFLD","C_STATUS":"INFLD","16":"Scheduled","CLASSIFICATION":"Scheduled","18":"TEST CABLE","TASK_DESCRIPTION":"TEST CABLE","19":"Reliability","TYPE_OF_WORK":"Reliability","20":"12-AUG-08","TS":"12-AUG-08","21":"12-AUG-08","TC":"12-AUG-08"}]
There is around 21 columns. How can I assign this to the columns in my dataTable?
This is my dataTable script:
var dataTables = $('#myTable').DataTable({
ajax: "test1.txt",
deferRender: true,
bPaginate: true,
select: {
style: 'multi'
},
aLengthMenu: [[100, 200, 500, -1], [100, 200, 500, "All"]],
pageLength: 100});

Make these changes in your datatable initialization.
ajax: {
url: "test1.txt",
dataSrc: ''
},
Remove columns: [ ]
You will then need to format your json text file such as this
[
{
"0" : "value of 1st column of 1st record",
"1" : "value of 2nd column of 1st record",
...
...
upto 21 column
},
{
"0" : "value of 1st column of 2nd record",
"1" : "value of 2nd column of 2nd record",
...
...
upto 21 column
}
]
Try this and see if it works.
If you want to hide column, then add this in datatable
"columnDefs": [
{
"targets": [ 0, 1 ],
"visible": false,
"searchable": false
}
]
Where 0, 1 represents you column index.
0 first column, 1 second column
Enter these index number of column which you want to hide.
New Update
In the dynamic json file case, you will need to use first approach using columns
Mention what columns you want to show in the columns key like below
$('#myTable').DataTable( {
"ajax": {
url: "test1.txt",
dataSrc: ''
},
"columns": [
{ "data": "C1" },
{ "data": "C2" }
]
});
and then your json text file will be like
[{"C1":"22352442","C2":"22126303","KEY":"NO SHOW"}, {"C1":"22352442","C2":"22126303", "KEY":"NO SHOW"}]
Your first json will work in the case now.

Related

Why do I have not necessary pagination buttons with jQuery DataTables?

I have a problem on a DataTables using pagination with server-side request.
It looks like the number of pagination buttons is not related to my results.
I always have buttons for pages 1, 2, 3, 4, 5, no matter how many results I have.
My DataTables definition:
$('#tableau_reponses').DataTable({
"ajax": {
url: '/my_api/get_reponses_ajax',
type: 'post',
data: formData
},
"paging": true,
"searching": false,
"bProcessing": true,
"serverSide": true,
"ordering": false,
"info": false,
"pagingType": "numbers",
"pageLength": 20,
"lengthMenu": [10, 20, 50, 100],
'order': [[1, 'asc']],
'columnDefs': [
{
'targets': 0,
'orderable': false,
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
},
{
'targets': 1,
'render': function (data) {
return '<td class="response_state_folder"></td>';
}
}
],
});
On my test environment, I know I have 29 results. My pageLength is set to 20.
So by default, on page 1, I have 20 results. When I select page 2, I have 9 results. So far so good.
But when I select page 3, 4 or 5 (and I shouldn't be able to) I have 0 results.
Why do I have "3, 4, 5" buttons when, with 29 results, I should have only 2 pages?
Of course if I have 142 results I need 8 pages...
I think I'm missing something pretty obvious here...
Thanks for your help!
===== EDIT =====
Following #Ashu's answer, I've managed to get "recordsFiltered" and "recordsTotal" in my response (respectively "20" and "29" in my example). But now, I have only one button (for page 1) where I'm expecting two.
Your server response must return how many rows are there in the filtered response from the database, and how many rows are there in total so as the database so it can set the pagination values right.
Example response :
{
"draw": 1,
"recordsTotal": 57, // these both are important and must be updated in every response
"recordsFiltered": 20, //
"data": [
[
"Angelica",
"Ramos",
"System Architect",
"London",
"9th Oct 09",
"$2,875"
],
]
}
If you need help on server-side code, You can edit or ask a new question.
More in the documentation here

Datatables sorting - how to ignore text in column?

I have used this script to sort my datatable and ignore text that I do not want to sort, I'll explain.
this is the column example:
10,836
↑(10.71%)
14,836
↑(13.71%)
I want to ignore this: ↑(10.71%) and to sort according to this: 10,836.
thats my script:
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"justNum-pre": a => parseFloat(a.replace(/\D/g, "")),
"justNum-asc": (a, b) => a - b,
"justNum-desc": (a, b) => b - a
});
$(document).ready(function () {
var table = $('#dataTable').DataTable({
order: [[ 1, "desc" ]],
scrollY: 200,
scrollX: false,
responsive: true,
paging: false,
//colReorder: true,
//pageLength: 100,
columns: [
{
"render": function(data, type, row){
return data.split(" ").join("<br/>");
}
},
null,
null,
null,
null,
null,
null
],
columnDefs: [
{ className: "all", "targets": [ 0, 1, 3, 6 ] },
{
type: 'justNum',
targets: 1
}
]
});
});
You can do this using the DataTables orderData feature.
For example, assume your formatted data is in the first column:
10,836
↑(10.71%)
Add a second column containing only the numeric portion (no text) 10836 and define it as a hidden column.
Then, create a columnDefs section in your datatable definition - something like this:
$('#demo').DataTable( {
"columnDefs": [
{ "orderData": [ 1 ], "targets": 0 },
{ "visible": false, "targets": 1 }
]
} );
} );
This says that the first column (target index 0) will use the data in the second column (target index 1) for sorting. And the second column will be a hidden column.

How to show just the N first number of rows on DataTables? How to download all data after this?

I am trying to show only the first N rows of data on DataTables, but can't find a way.
Additionally, when I click the Copy or Excel buttons I want to download all the data, and not just the rows who are being show.
In my last try, I used paging and pageLength without success. Below is the code. My data is on tbldata:
var dtable = $("#dvTableAC").DataTable({
data: tbldata,
columns: [
{ title: "A" },
{ title: "B" },
{ title: "C" },
{ title: "D" }
],
"paging": false,
"pageLength": 50,
dom: 'Blfrtip',
buttons: [
'excel', 'copy'
]
});
Please not that you need an extra plugin to be able to use the buttons (excel, copy).
https://datatables.net/extensions/buttons/built-in
var dtable = $("#dvTableAC").DataTable({
data: tbldata,
columns: [
{ title: "A" },
{ title: "B" },
{ title: "C" },
{ title: "D" }
],
"paging": true,
"pageLenght":10,
dom: 'Blfrtip',
buttons: [
'excel', 'copy'
]
});
Datatables will show all the data you send to it, if you set paging to false, then pageLenght is not used. If you want to limit the total records that datatables show, you must send just those records to it. You can restrict the number on the mysql query using limit 10. But I don't know any method of not having pagination and show only a x amount of rows from the total.

How to add a class to the <td> in server-side processing mode

When using server-side processing on a DataTable, there is a mechanism to add an ID, class, or data-* attribute to the table row (<tr>) by including the DT_RowId, DT_RowClass or DT_RowData properties, respectively, to the JSON data for each row: https://datatables.net/examples/server_side/ids.html.
Is there a similar (or any) mechanism for adding additional markup to the table columns (<td>)?
You can add classes to columns like so, but not sure if this gets you where you want to go:
var all_data = data;
$("#example").DataTable({
"data": all_data,
"aoColumns": [{
"data": 'cat_code',
"className": "lang_body_2",//you can add whatever you want for a specific column here.
"visible": false
}, {
"data": 'value',
"searchable": false,
"width": "20%",
"className": "lang_body_2",
"title": ""
}]
})
Other way, from off. sites docs.
Assign class my_class to first column
$('#example').dataTable( {
"columnDefs": [
{ className: "my_class", "targets": [ 0 ] }
]
} );

How to sort only certain columns

I am using jQuery DataTables plugin to sort table data. I have four columns: Name, Position, Office and Age. What I want is user to be able to sort only Name and Age columns, not all the columns. But I am not able to stop sorting on OTHER columns. Can you please suggest something?
This code disable sorting, 0 - index of column.
For old version
aoColumnDefs: [
{
bSortable: false,
aTargets: [ 0 ]
}
]
for DataTables 1.10+
columnDefs: [
{ orderable: false, targets: 0 }
]
Especially for example, you need this
$(document).ready(function() {
$('#example').dataTable( {
"order": [[ 0, "desc" ]],
"aoColumns": [
null,
{ "bSortable": false },
{ "bSortable": false },
null
]
} );
} );
fiddle

Categories

Resources