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.
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 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();
});
}
});
I am using https://github.com/yajra/laravel-datatables/ package
to show data within html table via ajax request and here is my settings
route
Route::get('dashboard/initiation-by-org', ['uses' =>'DashboardController#showTotalInitiationByOrganization']);
controller
public function showTotalInitiationByOrganization(){
$litigation = collect(Dashboard::countLitigationsOfAnOrganizationByCountry());
return Datatables::of($litigation)->make(true);
}
call data table
$('#organization-cases').DataTable({
processing: true,
serverSide: true,
aaSorting: [],
iDisplayLength: 6,
iDisplayStart: 0,
ajax: '/dashboard/initiation-by-org',
"columns": [
{'data': 'organization'},
{'data': 'litigations'}
]
});
**My json response**
{
"draw": 0,
"recordsTotal": 2,
"recordsFiltered": 2,
"data": [
{
"organization": "Shakti Samuha",
"litigations": 1
},
{
"organization": "CWIN",
"litigations": 1
}
],
"input": [
]
}
my table
<table id="organization-cases" class="table table-bordeard">
<thead>
<tr>
<th>Organization</th>
<th>Litigations</th>
</tr>
</thead>
</table>
I have install this package according to the installation manual but I did not get any data in my table.
please tell me What is the problem of this issue?
Thanks
Manoz
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();
}
})
so i am looking into loading external data in an select2 box where there is prepopulate results from the json
i have two issue - getting the data in and then only loading the first few but when a user searches it passes the request to the rest and then the specific json is returned
so the HTML is a simple as
<input type="hidden" id="e21" style="width:300px;"/>
the inital js is
$(document).ready(function () {
$('#e21').select2({
query: function (query){
var data = {results: []};
console.log(data);
$.each(preload_data, function(){
if(query.term.length == 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){
data.results.push({id: this.id, text: this.text });
}
});
query.callback(data);
}
});
$('#e21').select2('data', preload_data );
});
what that does is load in preload_data so that could be
var preload_data = [
{ id: 'user0', text: 'Disabled User'},
{ id: 'user1', text: 'Jane Doe'},
{ id: 'user2', text: 'John Doe', locked: true },
{ id: 'user3', text: 'Robert Paulson', locked: true },
{ id: 'user5', text: 'Spongebob Squarepants'},
{ id: 'user6', text: 'Planet Bob' },
{ id: 'user7', text: 'Inigo Montoya' }
];
an example is here
http://jsfiddle.net/dwhitmarsh/MfJ4B/10/
but instead of preload_data i want to load in load in a ajax call and pass the results
so i could use
var preload_data = $.ajax({
url: 'data/more.json',
method: 'get',
dataType: 'json'
});
but need to wait for the json to load and only want to load in the first 10.
then when a user actually searches i want to pass extra variables like
string: term, //search term
page_limit: 10, // page size
page: page // page number
page is part of the select 2
can anyone help?
btw the more.json looks like
{
"total": 8,
"result": [{
"id": "1",
"label": "Type",
"safeName":"type",
"jsonFile": "type.json"
},{
"id": "2",
"label": "Primary Applicant Name",
"safeName":"primaryApplicantName",
"jsonFile": "primary.json"
},{
"id": "3",
"label": "Address",
"safeName":"address",
"jsonFile": "address.json"
},{
"id": "4",
"label": "Product",
"safeName":"product",
"jsonFile": "product.json"
},{
"id": "5",
"label": "Verification",
"safeName": "verification",
"jsonFile": "verification.json"
},{
"id": "6",
"label": "Documents",
"safeName": "documents",
"jsonFile": "documents.json"
},{
"id": "7",
"label": "Suburb",
"safeName": "suburb",
"jsonFile": "suburb.json"
},{
"id": "8",
"label": "State",
"safeName": "state",
"jsonFile": "state.json"
}]
}