how to save my datatable data ASP.NET MVC 5 - javascript

I need to save all the data that is in my datatable
How could I add a general button that keeps everything in my datatable?
This in my current Project :
var table = $('#listaDocumentos').DataTable({
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf'
],
language: {
"decimal": "",
"emptyTable": "No hay información",
"info": "Mostrando _START_ a _END_ de _TOTAL_ Documentos",
"infoEmpty": "Mostrando 0 to 0 of 0 Documentos",
"infoFiltered": "(Filtrado de _MAX_ total entradas)",
"infoPostFix": "",
"thousands": ",",
"lengthMenu": "Mostrar _MENU_ Documentos",
"loadingRecords": "Cargando...",
"processing": "Procesando...",
"search": "Buscar:",
"zeroRecords": "Sin resultados encontrados",
"paginate": {
"first": "Primero",
"last": "Ultimo",
"next": "Siguiente",
"previous": "Anterior"
}
}
});
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.5.2/css/buttons.dataTables.min.css"> <script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.5.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.flash.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.html5.min.js"></script>
<table id="listaDocumentos" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Donna Snider</td>
<td>Customer Support</td>
<td>New York</td>
<td>27</td>
<td>2011/01/25</td>
<td>$112,000</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>

What i understand from your question is
you need to save data which is currently showing in the view(Html page) as tabular format.
In this case you can use jquery or javascript like below to get the data.
var table = $("table tbody");
table.find('tr').each(function (i) {
// comment loop through the tr and get value of every td within this tr tag
var tds = $(this).find('td');
var Name = $tds.eq(0).text();
var Position = $tds.eq(1).text();
var office = $tds.eq(2).text();
var age = $tds.eq(3).text();
var startPosition = $tds.eq(4).text();
var salary = $tds.eq(5).text();
});
Then bind a button in view like
<input type="button" id="btn_data_save" value="Save Data"/>
Then an ajax call to pass the data to server. WIthin that call you need to collect all the value and build an array of object.
$(document).on('click','#btn_data_save', function(){
var ary=[];
var table = $("table tbody");
table.find('tr').each(function (i) {
var obj={};
obj.tds = $(this).find('td');
obj.name = $tds.eq(0).text();
obj.position = $tds.eq(1).text();
obj.office = $tds.eq(2).text();
obj.age = $tds.eq(3).text();
obj.startPosition = $tds.eq(4).text();
obj.salary = $tds.eq(5).text();
ary.Push(obj);
});
$.ajax({
type: 'POST',
url: '',
data: { list: JSON.stringify(ary) },
dataType: 'json',
success: function (data) {
}
});
});
Finally in controller
[HttpPost]
public ActionResult SaveData(string list)
{
//comment do your work
}
Please comment if you do not understand the solution. i will describe if necessary.

Related

Expand/Collapse all with Nested Table - jQuery Datatables

I am using datatables plugin. I would like to ask, is there any way to expand/collapse all rows of the nested table. I tried to implement this below, but it doesn't work. I would like to expand/collapse rows like this example
https://www.gyrocode.com/articles/jquery-datatables-how-to-expand-collapse-all-child-rows/#regular.
Please help thanks
function fnFormatDetails(table_id, html) {
var sOut = "<table id=\"exampleTable_" + table_id + "\">";
sOut += html;
sOut += "</table>";
return sOut;
}
var iTableCounter = 1;
var oTable;
var oInnerTable;
var TableHtml;
//Run On HTML Build
$(document).ready(function () {
TableHtml = $('#exampleTable_2').html();
//Insert a 'details' column to the table
var nCloneTh = document.createElement('th');
var nCloneTd = document.createElement('td');
nCloneTd.innerHTML = '<img src="http://i.imgur.com/SD7Dz.png">';
nCloneTd.className = "center";
$('#exampleTable thead tr').each(function () {
this.insertBefore(nCloneTh, this.childNodes[0]);
});
$('#exampleTable tbody tr').each(function () {
this.insertBefore(nCloneTd.cloneNode(true), this.childNodes[0]);
});
//Initialse DataTables, with no sorting on the 'details' column
var oTable = $('#exampleTable').dataTable({
'bJQueryUI': true,
'sPaginationType': 'full_numbers',
'aoColumnDefs': [{
'bSortable': false,
'class': 'details-control',
'aTargets': [0]
}
],
'aaSorting': [[1, 'asc']]
});
/* Add event listener for opening and closing details
* Note that the indicator for showing which row is open is not controlled by DataTables,
* rather it is done here
*/
$('#exampleTable tbody tr img').on('click', function () {
var nTr = $(this).closest('tr');
if (oTable.fnIsOpen(nTr)) {
/* This row is already open - close it */
this.src = "http://i.imgur.com/SD7Dz.png";
oTable.fnClose(nTr);
} else {
/* Open this row */
this.src = "http://i.imgur.com/d4ICC.png";
oTable.fnOpen(nTr, fnFormatDetails(iTableCounter, TableHtml), 'details-control');
oInnerTable = $('#exampleTable_' + iTableCounter).dataTable({
'bJQueryUI': true,
'sPaginationType': 'full_numbers'
});
iTableCounter = iTableCounter + 1;
}
$('#btn-show-all-children').on('click', function () {
// Enumerate all rows
oTable.rows().every(function () {
// If row has details collapsed
if (!this.oTable.fnIsOpen(nTr)) {
/* Open this row */
this.src = "http://i.imgur.com/d4ICC.png";
this.oTable.fnOpen(nTr, fnFormatDetails(iTableCounter, TableHtml), 'details-control');
this.oInnerTable = $("#exampleTable_" + iTableCounter).dataTable({
'bJQueryUI': true,
'sPaginationType': 'full_numbers'
});
iTableCounter = iTableCounter + 1;
}
});
});
// Handle click on "Collapse All" button
$('#btn-hide-all-children').on('click', function () {
// Enumerate all rows
oTable.rows().every(function () {
// If row has details expanded
if (oTable.fnIsOpen(nTr)) {
/* This row is already open - close it */
this.src = "http://i.imgur.com/SD7Dz.png";
oTable.fnClose(nTr);
}
});
});
$('#btn-show-all-children').on('click', function () {
// Enumerate all rows
oTable.rows().every(function () {
// If row has details collapsed
if (!this.oTable.fnIsOpen(nTr)) {
/* Open this row */
this.src = "http://i.imgur.com/d4ICC.png";
this.oTable.fnOpen(nTr, fnFormatDetails(iTableCounter, TableHtml), 'details-control');
this.oInnerTable = $("#exampleTable_" + iTableCounter).dataTable({
'bJQueryUI': true,
'sPaginationType': 'full_numbers'
});
iTableCounter = iTableCounter + 1;
}
});
});
// Handle click on "Collapse All" button
$('#btn-hide-all-children').on('click', function () {
// Enumerate all rows
oTable.rows().every(function () {
// If row has details expanded
if (oTable.fnIsOpen(nTr)) {
/* This row is already open - close it */
this.src = "http://i.imgur.com/SD7Dz.png";
oTable.fnClose(nTr);
}
});
});
});
});
td.details-control {
background: url('https://cdn.rawgit.com/DataTables/DataTables/6c7ada53ebc228ea9bc28b1b216e793b1825d188/examples/resources/details_open.png') no-repeat center center;
cursor: pointer;
}
tr.shown td.details-control {
background: url('https://cdn.rawgit.com/DataTables/DataTables/6c7ada53ebc228ea9bc28b1b216e793b1825d188/examples/resources/details_close.png') no-repeat center center;
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables_themeroller.css">
<link rel="stylesheet" type="text/css" href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<!-- Col reorder with resize-->
<script src="colreorderwithresize.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
</head>
<body>
<button id="btn-show-all-children" type="button">Expand All</button>
<button id="btn-show-all-children" type="button">Collapse All</button>
<table id="exampleTable">
<thead>
<tr>
<th>Year</th>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td>2012</td>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>2012</td>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
<div style="display:none">
<table id="exampleTable_2" class="display select" width="100%">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
<th>Extn.</th>
<th>E-mail</th>
</tr>
</thead>
<tbody >
<tr>
<td>Tiger</td>
<td>Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
<td>5421</td>
<td>t.nixon#datatables.net</td>
</tr>
<tr>
<td>Garrett</td>
<td>Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
<td>8422</td>
<td>g.winters#datatables.net</td>
</tr>
</tfoot>
</table>
</div>
</body>
</html>
PROBLEM
There are too many issues with the code to list them all. For example:
Multiple versions of jQuery DataTables included - 1.9 and 1.10
Multiple versions of jQuery included: 1.11 and 3.5
DataTables 1.10 API method such as rows() are called on DataTables 1.9 instance, see API for more details.
Event handlers are assigned multiple times in incorrect places.
SOLUTION
Please see below the corrected code and adjust to the libraries that you're using.
function fnFormatDetails(table_id, html) {
var sOut = "<table id=\"exampleTable_" + table_id + "\">";
sOut += html;
sOut += "</table>";
return sOut;
}
var iTableCounter = 1;
var oTable;
var oInnerTable;
var TableHtml;
//Run On HTML Build
$(document).ready(function () {
TableHtml = $('#exampleTable_2').html();
//Insert a 'details' column to the table
var nCloneTh = document.createElement('th');
var nCloneTd = document.createElement('td');
$('#exampleTable thead tr').each(function () {
this.insertBefore(nCloneTh, this.childNodes[0]);
});
//Initialse DataTables, with no sorting on the 'details' column
var oTable = $('#exampleTable').dataTable({
'bJQueryUI': true,
'sPaginationType': 'full_numbers',
'aoColumnDefs': [{
'bSortable': false,
'class': 'details-control',
'aTargets': [0]
}
],
'aaSorting': [[1, 'asc']]
});
/* Add event listener for opening and closing details
* Note that the indicator for showing which row is open is not controlled by DataTables,
* rather it is done here
*/
$('#exampleTable tbody tr td.details-control').on('click', function () {
var nTr = $(this).closest('tr');
if (oTable.fnIsOpen(nTr)) {
oTable.fnClose(nTr);
} else {
oTable.fnOpen(nTr, fnFormatDetails(iTableCounter, TableHtml), 'details-control');
oInnerTable = $('#exampleTable_' + iTableCounter).dataTable({
'bJQueryUI': true,
'sPaginationType': 'full_numbers'
});
iTableCounter = iTableCounter + 1;
}
});
// Handle click on "Collapse All" button
$('#btn-hide-all-children').on('click', function () {
// Enumerate all rows
oTable.$('tr').each(function(index, nTr){
// If row has details expanded
if (oTable.fnIsOpen(nTr)) {
oTable.fnClose(nTr);
$(nTr).removeClass('shown');
}
});
});
$('#btn-show-all-children').on('click', function () {
// Enumerate all rows
oTable.$('tr').each(function(index, nTr){
// If row has details collapsed
if (!oTable.fnIsOpen(nTr)) {
/* Open this row */
oTable.fnOpen(nTr, fnFormatDetails(iTableCounter, TableHtml), 'details-control');
$(nTr).addClass('shown');
}
});
});
});
td.details-control {
background: url('https://cdn.rawgit.com/DataTables/DataTables/6c7ada53ebc228ea9bc28b1b216e793b1825d188/examples/resources/details_open.png') no-repeat center center;
cursor: pointer;
}
tr.shown td.details-control {
background: url('https://cdn.rawgit.com/DataTables/DataTables/6c7ada53ebc228ea9bc28b1b216e793b1825d188/examples/resources/details_close.png') no-repeat center center;
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.21/datatables.min.css">
<script type="text/javascript" charset="utf8" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<!-- Col reorder with resize-->
<script src="colreorderwithresize.js"></script>
<script src="https://cdn.datatables.net/v/dt/dt-1.10.21/datatables.min.js"></script>
</head>
<body>
<button id="btn-show-all-children" type="button">Expand All</button>
<button id="btn-hide-all-children" type="button">Collapse All</button>
<table id="exampleTable" class="display">
<thead>
<tr>
<th>Year</th>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>2012</td>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td></td>
<td>2012</td>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
<div style="display:none">
<table id="exampleTable_2" class="display select" width="100%">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
<th>Extn.</th>
<th>E-mail</th>
</tr>
</thead>
<tbody >
<tr>
<td>Tiger</td>
<td>Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
<td>5421</td>
<td>t.nixon#datatables.net</td>
</tr>
<tr>
<td>Garrett</td>
<td>Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
<td>8422</td>
<td>g.winters#datatables.net</td>
</tr>
</tfoot>
</table>
</div>
</body>
</html>
LINK
Please see jQuery DataTables: How to expand/collapse all child rows for more information and examples.

Get attribute value from datatables row for every record

I am working with datatables and I want to edit and delete data table records
When I do console.log(row) following output I get:
["user1", "Edit"]
(index):274 (2) ["user2", "Edit"]
(index):274 (2) ["user3", "Edit"]
(index):274 (2) ["user4", "Edit"]
(index):274 (2) ["user5", "Edit"]
What I want is to get data-id from render: function (data, type, row) which I have used in datatable script and when click on edit button I want to get specific id in alert but I am unable to extract data-id.
My jQuery code:
$.fn.dataTable.ext.errMode = 'none';
var table = $('#catgeory_list').DataTable({
processing: true,
language: {
emptyTable: 'no result found.'
},
columnDefs: [{
visible: true,
targets: 0,
render: function (data, type, full, meta) {
return data;
}
}, {
visible: true,
targets: 1,
render: function (data, type, row) {
console.log(row);
return '<button id="editBtn" class="btn btn-wrang btn-flat edit" name="editBtn" type="button">Edit</button>' + ' <button id="deleteBtn" class="btn btn-danger btn-flat delete" name="deleteBtn" type="button" >Delete</button>';
}
}
],
});
In order to get any source object/array property/item for the row being clicked, you don't need anything more than simple row().data() API method invoked against DataTable row (selected by the closest to the clicked button <tr> node):
$('table').on('click', 'tbody td button', function(){
const rowData = dataTable.row($(this).closest('tr')).data();
alert(`Row ID is ${rowData.id}`);
});
Here, dataTable is a variable, you assign your DataTable to.
Full-blown DEMO you might find below.
Also, considering your ultimate goal, you might find of use my answer over here, which provides complete working demo of editable DataTable. So, if you find that helpful, upvotes are appreciated ;)
//src data
const srcData = [
{id: 1, item: 'apple'},
{id: 2, item: 'banana'},
{id: 3, item: 'tomato'}
];
//datatables init
const dataTable = $('table').DataTable({
dom: 't',
data: srcData,
columns: [{data: 'item', title: 'Item Name', render: data => data+'<button>Show Id</button>'}]
});
//click handler
$('table').on('click', 'tbody td button', function(){
const rowData = dataTable.row($(this).closest('tr')).data();
alert(`Row ID is ${rowData.id}`);
});
td button {float: right}
<!doctype html><html><head><link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/rg-1.1.0/datatables.min.css" /><script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script><script type="text/javascript" src="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/rg-1.1.0/datatables.min.js"></script></head><body><table></table></body></html>
You can wrap data or row parameter from callback function with jQuery $() to get any element/node attributes or DOM manipuation. Refer also toJQuery() for dealing with Datatables API instances.
Render
render: function(data, type, row, meta){
var data_id = $(data).data('id');
console.log('Columns.Render:',data_id);
return data + " : data-id(" + data_id+")";
}
createdRow
createdRow: function (row, data, index) {
var data_id = $('td a.edit_row', row).data('id');
console.log('CreatedRow:',data_id);
}
Click Event
$("a.edit_row").click(function(){
var data_id = $(this).data('id');
alert(data_id);
});
Working Live Demo:
$(document).ready( function () {
var table = $('#example').DataTable({
columnDefs: [
{
targets: 1,
render: function(data, type, row, meta){
var data_id = $(data).data('id');
console.log('Columns.Render:',data_id);
return data + " : data-id(" + data_id+")";
}
},
],
createdRow: function (row, data, index) {
var data_id = $('td a.edit_row', row).data('id');
console.log('CreatedRow:',data_id);
}
});
$("a.edit_row").click(function(){
var data_id = $(this).data('id');
alert(data_id);
});
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css"
rel="stylesheet" type="text/css" />
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="example" class="display nowrap" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>Edit</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$3,120</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Edit</td>
<td>Edinburgh</td>
<td>63</td>
<td>2011/07/25</td>
<td>$5,300</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Edit</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$4,800</td>
</tr>
</tbody>
</table>

Jquery Datatables Individual column searching

I am trying to apply Individual column searching (select inputs) for Datatables plugin in Jquery. I am using serverside processing, the data is loaded correctly from SQL Server into my table but when I want to select an input to filter a column based on that value, the filter is not working as you see here.
When I select a country for example Austria, the data is not filtered to Austria.
Here is my index page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset=utf-8" />
<title> Datatables Individual column searching using PHP Ajax Jquery </title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1 align="center">Datatables</h1>
<div class="table-responsive">
<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Country</th>
<th>Territory</th>
<th>Market</th>
<th>Entname</th>
<th>MTM</th>
<th>Qty</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Country</th>
<th>Territory</th>
<th>Market</th>
<th>Entname</th>
<th>MTM</th>
<th>Qty</th>
</tr>
</tfoot>
</table>
</div>
</div>
</body>
</html>
<script type="text/javascript" language="javascript" >
$(document).ready(function() {
var dtable = $('#example').DataTable({
"processing": true,
"serverSide": true,
"deferRender": true,
"lengthMenu": [ [25, 50, 100, -1], [25, 50, 100, "All"] ],
"pageLength": -1,
"lengthChange": true,
"pagingType": "full_numbers",
"columns": [
{"data": "Country"},
{"data": "Territory"},
{"data": "Market"},
{"data": "Entname"},
{"data": "MTM"},
{"data": "Qty"}
],
"ajax": {
url: 'fetch.php',
type: 'POST'
},
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
}
});
$(".dataTables_filter input")
.unbind()
.bind("keyup change", function(e) {
if(this.value.length >= 1 && e.keyCode == 13) { dtable.search(this.value).draw(); }
if(this.value == "") { dtable.search("").draw(); }
return;
});
} );
</script>
and here is my fetch.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (!empty($_POST) ) {
$ser="*****";
$db="*****";
$user="*****";
$pass="*****";
$dbDB = new PDO("odbc:Driver=ODBC Driver 13 for SQL Server;Server=*****;Database=*****;Port=1456", $user, $pass);
$MyTable="*****";
function getData($sql){
global $dbDB ;
global $MyTable ;
$result = $dbDB->query($sql);
$data= $result->fetchAll(PDO::FETCH_ASSOC);
return $data; }
$res = $dbDB->query("SELECT COUNT(*) FROM ".$MyTable);
$recordsTotal = $res->fetchColumn();
$draw = $_POST["draw"];
$orderByColumnIndex = $_POST['order'][0]['column'];
$orderBy = $_POST['columns'][$orderByColumnIndex]['data'];
$orderType = $_POST['order'][0]['dir'];
$start = $_POST["start"];
if ($_POST['length'] == -1) {$length = $recordsTotal;}
else {$length = $_POST['length'];}
if(!empty($_POST['search']['value'])){
for($i=0 ; $i<count($_POST['columns']);$i++){
$column = $_POST['columns'][$i]['data'];
$where[]="$column like '%".$_POST['search']['value']."%'";
}
$where = "WHERE ".implode(" OR " , $where);
$sql = sprintf("SELECT COUNT(*) FROM %s %s", $MyTable , $where);
$r = $dbDB->query($sql);
$recordsFiltered = $r->fetchColumn();
$sql = sprintf("SELECT Country,Territory,Market,Entname,MTM,Qty FROM %s %s ORDER BY %s %s OFFSET %d ROWS FETCH NEXT %d ROWS ONLY", $MyTable , $where ,$orderBy, $orderType ,$start,$length);
$data = getData($sql);
}
else {
$sql = sprintf("SELECT Country,Territory,Market,Entname,MTM,Qty FROM %s ORDER BY %s %s OFFSET %d ROWS FETCH NEXT %d ROWS ONLY", $MyTable ,$orderBy, $orderType ,$start,$length);
$data = getData($sql);
$recordsFiltered = $recordsTotal;
}
$response = array(
"draw" => intval($draw),
"recordsTotal" => $recordsTotal,
"recordsFiltered" => $recordsFiltered,
"data" => $data );
echo json_encode($response);
}
else {
echo "NO POST Query from DataTable";
}
?>
I believe that the issue is somewhere in the javascript part not the php file but just to show an overview how the data is populated into the table.
Any idea please where is the issue?
Check below example
// Setup - add a text input to each footer cell
$('#item tfoot th').each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
// DataTable
var otable = $('#item').DataTable();
// Apply the search
otable.columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );
} );
tfoot {
display: table-header-group;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://www.jqueryscript.net/demo/DataTables-Jquery-Table-Plugin/media/css/jquery.dataTables.css">
<table name="item" id="item" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$86,000</td>
</tr>
<tr>
<td>Cedric Kelly</td>
<td>Senior Javascript Developer</td>
<td>Edinburgh</td>
<td>22</td>
<td>2012/03/29</td>
<td>$433,060</td>
</tr>
<tr>
<td>Airi Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>33</td>
<td>2008/11/28</td>
<td>$162,700</td>
</tr>
</tbody>
</table>
what about datefilter search i.e enddate>startdate to this datatable.It would more convenient.

Jquery datatables button not working?

Here is my screenshot :
This is my following code:
<link href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/buttons/1.2.4/css/buttons.dataTables.min.css" rel="stylesheet">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script
<Script src="https://cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js"></script>
<script>
$(document).ready(function() {
$('#example').DataTable( {
dom: 'Bfrtip',
buttons: [
{
text: 'My button',
action: function ( e, dt, node, config ) {
alert( 'Button activated' );
}
}
]
} );
} );
</script>
I'm trying to use this code from https://datatables.net/extensions/buttons/custom. I dont why my button button didn't show up. I was wondering why this code is not working. Can anyone please tell me how to use 'jQuery DataTables Button'?
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js"></script>
you have script error. try this one.
Screenshot:
http://prntscr.com/eazm0r
You have not properly closed script tag you have a missing > from below script tag
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>

scope = row not recognised in javascript code (jquery.visualize plugin)

I display a chart but I have to specify that my th column is (scope=row) in javascript code.
The chart used in this manner, Html code (example of using) :
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script language="javascript" type="text/javascript" src="jquery.visualize.plugin.js"></script>
<link type="text/css" rel="stylesheet" href="base.css"/>
<link type="text/css" rel="stylesheet" href="jquery.visualize.plugin.css"/>
<script type="text/javascript">
$(function(){
$('table').visualize({type: 'line'}).appendTo('body');
});
</script>
</head>
<body>
<table>
<caption>2009 Employee Sales by Department</caption>
<thead>
<tr>
<td></td>
<th scope="col">2010</th>
<th scope="col">2011</th>
<th scope="col">2012</th>
<th scope="col">2013</th>
<th scope="col">2014</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Gastro</th>
<td>10</td>
<td>20</td>
<td>30</td>
<td>40</td>
<td>50</td>
</tr>
<tr>
<th scope="row">Pneumo</th>
<td>20</td>
<td>30</td>
<td>20</td>
<td>40</td>
<td>40</td>
</tr>
<tr>
<th scope="row">Procto</th>
<td>80</td>
<td>90</td>
<td>60</td>
<td>100</td>
<td>90</td>
</tr>
</tbody>
</table>
</body>
</html>
You can see that in tbody, for the th tags, we used scope="row".
I use a datatTable to fill the table and I want to know how to specify it in javascript code.
My javascript code :
function fillDataTable(data) {
if ($("#table_campaigns").css("visibility") == "hidden")
$("#table_campaigns").css("visibility", "visible");
$('#table_campaigns').dataTable({
'aaData': data,
'aoColumns': [
{ "sTitle": "", "sCellType": "th", "fnCreatedCell": function (cell) { cell.scope = 'row';}},
{ "sTitle": "2010" },
{ "sTitle": "2011" },
{ "sTitle": "2012" },
{ "sTitle": "2013" },
{ "sTitle": "2014" }
],
"iDisplayLength": 10,
"bJQueryUI": true,
"bDestroy": true,
"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bSort": false,
"bInfo": false,
"bAutoWidth": false
});
}
I tested too $(tbody>th).attr('scope','row') but in vain.
Here is my chart :
This way works for me:
$('table tbody th').attr('scope','row');
You only want to use > when looking for direct childrens. th is not a direct children of tbody.
Also, you need to add quotes.
Live example

Categories