I am working on datatable .i want pagination on search for example i have a datatable with pagination . i have a search option but pagination does not work on search
<input class="btn btn-secondary" type="button" value="Show TheResults" id="theBtnSearch" />
$("#theBtnSearch").click(function () {
if ($.fn.dataTable.isDataTable('#thedatatab')) {
table = $('#thedatatab').DataTable();
//https://datatables.net/reference/api/ajax.reload()
table.ajax.reload();
}
});
<div class="DataTableClass" id="TheHeaderStyle" style="width: 100%">
<table id="thedatatab'" class="display table table-striped table-bordered">
<thead>
<tr>
<th><%: Html.DisplayNameFor(r => r.fieldA)%></th>
<th><%: Html.DisplayNameFor(r => r.fieldB)%></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
The method that gets called into
public JsonResult GetTheData(DTParameters param)
{
try
{
//call stored procedure with parms from DTParameters
//DTParameters comes with your datatables download, if you did it right
return Json(result);
}
}
Your DataTable declaration
$('#thedatatab').DataTable({
"pagingType": "full",
"serverSide": true,
"oLanguage": {
"sSearch": "Filter Search Results:" //http://legacy.datatables.net/usage/i18n#oLanguage.sSearch
},
"ajax": {
"type": "POST",
"url": '/Case/GetTheData',
"contentType": 'application/json; charset=utf-8',
'data': function (data) {
//http://stackoverflow.com/questions/24499116/how-to-pass-parameters-on-reload-of-datatables
//all the search parms here
data.searchParm = $("#searchParm").val();
return data = JSON.stringify(data);
}
},
"processing": true,
"columns": [
{ "data": "fieldA" },
{ "data": "fieldB" },
],
columnDefs: [
{
"targets": [0],
"visible": false,
"searchable": false
}
],
"order": [1, "desc"]
, "createdRow": function (row, data, index) {
$(row).click(function () {
$("#ajaxSpinner").removeClass("HideMeDisplay");
$("#TheHiddenRowNumber").val(data.FieldA)
$("form").submit();
});
}
});
Related
This is my working cshtml with ajax. Currently $(function () { loaddata();}) is what initializes the DataTable and "url": '/LoadData'() posts to the controller. But I need it to Post only when validation passes. I still need the Datatable to initialize though. When the document is ready I would like to initialize the Datatable just not LoadData. Post should automatically happen when validation passes.
button onclick="test()">RefreshData</button>
<table id="tblList" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>a</th>
<th>b</th>
<th>c</th>
<th>d</th>
</tr>
</thead>
</table>
js:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
function test() {
$('#tblList').DataTable().ajax.reload();
}
function validationfailure() {
//$('#firstname').val()=="";
return 'please enter a valid name'
}
function loaddata() {
var data = {};
data.id = $("#id").val();
$('#tblList').DataTable({
destroy: true,
ajax: {
"type": "POST",
"url": '/LoadData',
"dataType": "json",
"data": function(d) {
d.id = $("#id").val();
}
},
columns: [
{ "data": "a", responsivePriority: 1, "searchable": true },
{ "data": "b", responsivePriority: 2, "searchable": true },
{ "data": "c", responsivePriority: 3, "searchable": true },
{ "data": "d", responsivePriority: 4, "searchable": true },
],
});
};
$(function() {
if(!validationfailure)
loaddata();
})
action:
[HttpPost]
[Route("LoadData")]
public IActionResult GetFinanceiro(SearchModel s)
{
List<DataTableModel> l = new List<DataTableModel> {
new DataTableModel{ a="a1"+s.Id,b="b1"+s.Id,c="c1"+s.Id,d="d1"+s.Id},
new DataTableModel{ a="a2",b="b2",c="c2",d="d2"},
new DataTableModel{ a="a3",b="b3",c="c3",d="d3"},
new DataTableModel{ a="a4",b="b4",c="c4",d="d4"},
};
return Json(new { data = l });
}
I am implementing jquery DataTable with server-side pagination. Refer code snippet below -
Script
$(async function() {
$('#registry_table').DataTable({
serverSide: true,
ajax: {
url: 'localhost:3000/provenance/registries',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem("token")
},
data: () => {
return {page: 0, per_page: 5};
}
},
columns: [
{data: 'name', defaultContent: 'N/A'},
{data: 'created', defaultContent: 'N/A'},
{data: 'extrinsic', defaultContent: 'N/A'},
{data: 'registry', defaultContent: ' <span class="text-primary bg-white fa-border d-inline-block" style="cursor: pointer" title="Rename Registry"><i class="fas fa-pen-nib"/> Rename</span>'}
],
language: {
searchPlaceholder: "Search...",
search: "",
lengthMenu: "_MENU_ items/page"
}
});
});
Html
<table class="table table-striped mg-b-0" id="registry_table">
<thead>
<tr>
<th class="text-left">#</th>
<th class="text-left">Name</th>
<th class="text-left">Created on</th>
<th class="text-left">Transaction</th>
<th class="text-center">Action</th>
</tr>
</thead>
</table>
API response
{
"registries": [
{
"registry": 489607958,
"created_by": "5DqdTHZLA8X2Lk2FqCPFM9kxd8GmdMbyboFiFg6gmB8sHCg4",
"name": "test 7",
"created": "2020-09-14T15:08:49.006766"
},
{
"registry": 1421927575,
"created_by": "5DqdTHZLA8X2Lk2FqCPFM9kxd8GmdMbyboFiFg6gmB8sHCg4",
"name": "test 6",
"created": "2020-09-14T15:08:43.104835"
},
{
"registry": 1560576458,
"created_by": "5DqdTHZLA8X2Lk2FqCPFM9kxd8GmdMbyboFiFg6gmB8sHCg4",
"name": "test 4",
"created": "2020-09-14T15:08:34.132407"
},
{
"registry": 1766285412,
"created_by": "5DqdTHZLA8X2Lk2FqCPFM9kxd8GmdMbyboFiFg6gmB8sHCg4",
"name": "test 5",
"created": "2020-09-14T15:08:27.376323"
},
{
"registry": 155398053,
"created_by": "5DqdTHZLA8X2Lk2FqCPFM9kxd8GmdMbyboFiFg6gmB8sHCg4",
"name": "test 3",
"created": "2020-09-14T15:08:16.768747"
}
],
"total": 7
}
If the total number of rows is 7 and per_page = 5, then it should show 2 pages. But in the browser, it shows 5 pages. Also, page info shows wrong information.
Browser
My questions are-
Is there a way to set the number of pages/total items once data fetched
Page info should be Showing 1 to 5 of 7 entries (filtered from 7 total entries), how to set those properly?
How to pass the entire row as a parameter to a function (rename button)
Note: API is in production and unlikely to change.
Update 1:
Script (modified data and added dataSrc with ajax section
data: (d) => {
d.page =self.page;
d.per_page =self.per_page;
delete d.columns;
delete d.order;
delete d.search;
delete d.start;
delete d.length;
},
dataSrc: (response) => {
response.draw = 1;
response.recordsTotal = response.total;
response.recordsFiltered = response.registries.length;
response.data = response.registries;
return response.data;
}
Now it doesn't show any data but, everything else is fine.
I am using yajra datatables:
var table = $("#dt_user_draw").DataTable({
destroy: true,
processing: true,
responsive: true,
serverSide: true,
ordering: false,
"ajax": {
"method": "GET",
"url": 'url'
},
"columns": [
{
"data": "user"
},
{
"data": "email"
},
{
"data": "registered_at",
},
{
"render": function (data, wea, row) {
return '<i v-on:click="showDrawUser" class="nav-icon far fa-eye fa-fw " aria-hidden="true" title="Ver Draw"></i>';
}
},
]
});
In the last row, add v-on:click but this is not working. I do not how to do to vue render after datatables load
I have hosted one website in our company server.
In localhost I can access to all tables fine.
However in the hosted one when I click the link and that page contains tables gives me error:
** Message from webpage **
DataTables warning: table id=datatable-questionnaires - Ajax error. For more information about this error, please see http://datatables.net/tn/7
however I don't know how to fix this... how to solve this issue
edited:
`
var handleDataTables = function () {
var catId = $('#catId').val();
var typeId = $('#typeId').val();
$('#datatable-questions').dataTable({
"serverSide": true,
"ajax": {
"url": "handlers/_getQuestions.asp?catId=" + catId + "&typeId=" + typeId
},
"aoColumns": [
{
"bSortable": false
}
],
"fnInitComplete": function (oSettings, json) {
$('#datatable-questions_filter').append(" <button class='btn btn-sm btn-default' data-toggle='modal' data-target='#questionAddModal'>Criar Pergunta</button>");
}
});
$('#datatable-users').dataTable({
"serverSide": true,
"ajax": {
"url": "handlers/_getUsers.asp?"
},
"aoColumns": [
null,
null,
null,
{
"bSortable": false
}
],
"fnInitComplete": function (oSettings, json) {
$('#datatable-users_filter').append(" <button class='btn btn-sm btn-default' data-toggle='modal' data-target='#userAddModal'><span class='glyphicon glyphicon-user' aria-hidden='true'></span> Criar Novo</button>");
}
});
$('#datatable-questionnaires').dataTable({
"serverSide": true,
"ajax": {
"url": "handlers/_getQuestionnaires.asp?typeId=" + typeId
},
"aoColumns": [
null,
null,
null,
{
"bSortable": false
},
{
"bSortable": false
},
null
],
"fnDrawCallback": function () {
var $qActivate = $('.qActivate');
$qActivate.change(function () {
var isCheck = $(this).is(":checked");
var id = $(this).data('id');
jQuery.ajax({
data: {
id: id,
mode: isCheck
},
url: '../handlers/_activateQuestionnaire.asp',
type: 'POST'
});
});
},
"fnInitComplete": function (oSettings, json) {
$('#datatable-questionnaires_filter').append(" <a class='btn btn-sm btn-default' href='create_questionnaire.asp'><span class='glyphicon glyphicon-share-alt' aria-hidden='true'></span> Criar Novo</a>");
}
});
}
I'm trying to populate a table on a button click, getting the data from an ASP.NET ApiController. I've tried with almost all solutions posted in SO to other similar issues but always get that error.
Hope someone sees the problem.
The html markup:
<input type="button" ID="btnSearch" name="btnSearch" class="btn btn-success" value="Buscar" />
<table id="ResultsTable" class="table table-bordered table-condensed" style="font-size: 11px;">
<thead>
<tr>
<th><%=GetLiteral("Codigo")%></th>
<th><%=GetLiteral("Descripcion")%></th>
<th><%=GetLiteral("Marca")%></th>
<th><%=GetLiteral("IC")%></th>
<th><%=GetLiteral("IV")%></th>
<th><%=GetLiteral("Tarifa")%></th>
<th><%=GetLiteral("Precio")%></th>
<th><%=GetLiteral("P")%></th>
<th><%=GetLiteral("Total")%></th>
<th><%=GetLiteral("Central")%></th>
<th><%=GetLiteral("Centro")%></th>
</tr>
</thead>
<tbody>
</tbody>
The JS:
$(document).ready(function () {
var SearchTable = $("#ResultsTable").DataTable({
columns: [
{ data: "pCodigo" },
{ data: "rDescripcion" },
{ data: "rMarca" },
{ data: "xIndiceCarga" },
{ data: "xIndiceVelocidad" },
{ data: "TARIFA" },
{ data: "PRECIO" },
{ data: "PROVIENE" },
{ data: "TOTAL" },
{ data: "CENTRAL" },
{ data: "CENTRO" }
],
ordering: false,
searching: false
});
$("#btnSearch").click(function () {
var searchText = $("#<%=txtSearch.ClientID%>").val();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("~/api/ProductSearch/")%>' + searchText + '/0138107',
dataType: "json"
}).success(function(result) {
SearchTable.clear().draw();
SearchTable.rows.add(result).draw();
}).fail(function(jqXHR, textStatus, errorThrown) {
alert("FAIL: " + textStatus + " = " + errorThrown);
});
});
}
A data sample:
[{
"RowError": "",
"RowState": 2,
"Table": [{
"pCodigo": "10006908",
"rDescripcion": "225/65/16-VAN100(112R)CO B-B-72-2",
"rMarca": "CONTI",
"xDibujo": 254176,
"xIndiceCarga": "112",
"xIndiceVelocidad": "R",
"xEje": 0,
"xAplicacion": 0,
"xDecimales": false,
"xTipoIVA": 2,
"xTasa": 2.550,
"TARIFA": 203.50,
"PRECIO": 105.54,
"PROVIENE": "LG",
"COLOR": 8454143,
"TOTAL": 3.00,
"CENTRAL": 2.00,
"CENTRO": 2.00,
"xControl": true
},
{
"pCodigo": "30000159",
"rDescripcion": "225/65/16-RF09(112R)ROTALLA E-C-73-3",
"rMarca": "ROTAL",
"xDibujo": 253405,
"xIndiceCarga": "112",
"xIndiceVelocidad": "R",
"xEje": 0,
"xAplicacion": 0,
"xDecimales": false,
"xTipoIVA": 2,
"xTasa": 2.550,
"TARIFA": 69.00,
"PRECIO": 49.29,
"PROVIENE": "LG",
"COLOR": 16777088,
"TOTAL": 89.00,
"CENTRAL": 55.00,
"CENTRO": 55.00,
"xControl": true
}],
"ItemArray": ["30000159",
"225/65/16-RF09(112R)ROTALLA E-C-73-3",
"ROTAL",
253405,
"112",
"R",
0,
0,
false,
2,
2.550,
69.00,
49.29,
"LG",
16777088,
89.00,
55.00,
55.00,
true],
"HasErrors": false
}]
Note: The GetLiteral function in html markup returns a string with the column name internationalized, that can be different from the text shown and column name. I think that's not the problem.
Thanks in advance!
You must insert the Table array :
}).success(function(result) {
SearchTable.clear().draw();
SearchTable.rows.add(result[0].Table).draw();
})
alternatively you can cycle through the Table array and add each item individually :
}).success(function(result) {
SearchTable.clear().draw();
for (var i=0;i<result.Table.length;i++) {
SearchTable.row.add(result[0].Table[i]).draw();
}
})