implement server side pagination on datatable - javascript

inside mvc controller I'm receiving MyTable as parameter
public JsonResult GetListOfData(JobTable result)
{
var query = ... get data ..
IQueryable<MyData> resData;
resData.recordsFiltered = query.Skip(result.start).Take(50).AsQueryable();
resData.recordsTotal = query.Count();
...
return Json(resData, JsonRequestBehavior.AllowGet);
}
Inside view I have js code which initialize jquery data table
function drawTable() {
var table = $('#myTable').dataTable({
processing: true,
serverSide: true,
searching: false,
lengthChange: false,
displayLength: 25,
order: [[5, 'desc']],
ajax: {
url: '#Url.Action("GetListOfData", "Index")',
data: function (d) {
...
d.status = $('#Status').val(),
d.dateFrom = $('#DateFrom').val(),
d.dateTo = $('#DateTo').val(),
...
}
},
columns: [
{ data: 'Id' },
{ data: 'Status' },
{ data: 'CreatedDate' },
...
],
columnDefs: [
{
targets: [0, 3, 4],
orderable: false
},
{
render: function (data, type, row) {
return '<i class="glyphicon glyphicon-folder-open"></i>'
},
title: '',
targets: 0
}
]
});
}
Question is:
What I'm missing here to successfully implement server side pagination, what should I do to recognize clicked number inside view and receive that as part of MyTable parameter?

i just fixed it!!
recordFiltered and recordsTotal should be of same length.
i was doing at serverside :
return Json(new
{
draw = param.draw,
recordsTotal = allData.Count(),
recordsFiltered = filteredData.Count(),
data = result
}, JsonRequestBehavior.AllowGet);
now i did:
return Json(new
{
draw = param.draw,
recordsTotal = allData.Count(),
recordsFiltered = allData.Count(),
data = result
}, JsonRequestBehavior.AllowGet);

Related

API in javascript is returning data, but is not being saved into an array

I am trying to fetch data from an API of WordPress. Here is my code:
column.data().unique().sort().each(function (d,j) {
var practiceArea = d.practice_area;
var jsonPacticeArea = JSON.stringify(practiceArea);
if (jsonPacticeArea !== undefined) {
var res = $.map(jsonPacticeArea.split("|"), $.trim);
for (var i = 0; i < res.length; i++) {
var str = res[i];
str = str.replace(/"/gi, '').trim();
if (arrayPracticeArea.indexOf(str) === -1) {
arrayPracticeArea.push(str);
}
}
}
});
the "column" is the variable that is getting data through an API, and as far as I do console.log(column. data().unique().sort()), that's returning complete data as you can see in the screenshot:
[![enter image description here][1]][1]
and I want to fetch data is marked in red rectangle and store those values in an array, but as soon as I try to add "each" function to fetch the data and store it in an array (in my case its arrayPracticeArea) its returning undefined values.
Can anyone please help me out? I am just not much experienced with Javascript API.
Here is my AJAX code:
var tableAttorney = $('#table_affliate_attorney').DataTable({
destroy: true,
searching: true,
bLengthChange: false,
scrollX: true,
scrollY: 440,
autoWidth: false,
"language": {
"emptyTable": "We are sorry but there are no Affiliate Attorneys within a 150 mile radius of your requested search"
},
ajax: {
type: 'get',
url: "/wp-admin/admin-ajax.php",
dataType: 'json',
cache: false,
data: {
'action': 'get_attorney_ajax',
'center_lat': center_lat,
'center_long': center_long,
'state': state,
'city': city,
'zip': zip
}
},
columns: [
{"data": "title"},
{"data": "city"},
{"data": "state"},
{"data": "zip"},
{"data": "distance"},
{
"data": "phone",
className: 'datatablePhone',
render: function (data) {
return '' + data + '';
}
},
{
"data": "email",
className: 'px190EM',
render: function (data) {
return '' + data + '';
}
},
{
className: 'js-practice-area',
"data": "practice_area"
},
{
"targets": -1,
"data": 'email',
render: function (data) {
return "<a class='contact-lawyer' href='#' data-toggle='modal' data-target='#exampleModal' data-whatever='#mdo' data-email='"+data+"'>Contact</a>";
}
},
],
columnDefs: [
{"width": "150px", "targets": [0]},
{"width": "130px", "targets": [5]}
],
So I am trying to fetch data from columns->data that has value practice_area.
Here is the fiddle link where I have hosted my whole JS code: https://jsfiddle.net/fareeboy/apor08jn/1/
[1]: https://i.stack.imgur.com/4EOZS.png

Unable To Display Json Data in html Table Using jquery DataTable

i have C# function That Return Me Json Formated Data , function is below
void DisplayProjectMasterList()
{
string JSONString = "";
DataTable Dt = DB.GetDataTable("Sp_GetProjectMasterList");
if (Dt.Rows.Count > 0)
{
JSONString = JsonConvert.SerializeObject(Dt);
}
Context.Response.Write(JSONString);
}
and I am Calling This Function Via Ajax .in console i am getting json data But i dont know how to pass it to Jquery data table to display.. below is the javascript function... please help Me
function DisplayProjectMasterList() {
$.ajax({
url: 'project-master.ashx',
type: "POST",
dataType: 'json',
data: {
'fun': 'DisplayProjectMasterList'
},
success: function (data) {
console.log(data);
if (Chk_Res(data.errorMessage) == false) {
$('#tbl').dataTable({
paging: true,
sort: true,
searching: true,
scrollY: 200,
data: data,
columns: [
{ 'data':data.Prj_Id },
{ 'data':data.Prj_No },
{ 'data':data.Prj_Name },
{ 'data':data.Cus_Company_Name },
{ 'data':data.Prj_StartDate },
{ 'data':data.Prj_CompletionDate },
]
});
}
}
});
}
i am Getting FOllowing error while doing So:
DataTables warning: table id=tbl - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
Hi make sure the data you are being returned is in the following format:
{
"data": [
{
"Prj_Id": 1,
"Prj_No": 1,
"Prj_Name": "name",
"Cus_Company_Name": "company",
"Prj_StartDate": "2011/04/25",
"Prj_CompletionDate": "2011/04/25"
},
{
"Prj_Id": 1,
"Prj_No": 1,
"Prj_Name": "name",
"Cus_Company_Name": "company",
"Prj_StartDate": "2011/04/25",
"Prj_CompletionDate": "2011/04/25"
}
]
}
jquery Datatables by default looks for data property for the array of objects
https://datatables.net/reference/option/ajax.dataSrc
https://datatables.net/examples/ajax/objects.html

Fill WebGrid with dataset

I have problems returning my DataSet to my WebGrid, previously I was filling it with a connection to my Entity and I had no problems, the fact is that for security reasons in my work I can not use more than a connection already "Default"
before:
using (SiniestrosEntities dc = new SiniestrosEntities())
{
var Condicion = dc.CAT_Doctos_Proveedores.OrderBy(a =>
a.id_Proveedor).ToList();
return Json(new
{
data = Condicion
}, JsonRequestBehavior.AllowGet);
}
Returning my data to my View, I had no problem.
Now I have my database query in a DATSET and I want to return it with a Json to my view ... but I get the following error:
DataTables warning: table id=myDatatable - Requested unknown parameter 'nFacturaProveedoresID' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
My Code JS
var oTable = $('#myDatatable').DataTable({
"ajax": {
"url": '/Facturas/GetEmployees',
"type": "get",
"datatype": "json"
},
"columns": [
{ "data": "nFacturaProveedoresID", "autoWidth": true },
{ "data": "nSiniestroid", "autoWidth": true },
{ "data": "cSerie", "autoWidth": true },
{ "data": "cFolio", "autoWidth": true },
{ "data": "dtFechaFactura", "autoWidth": true },
{ "data": "cConcepto", "autoWidth": true },
{ "data": "mTotal", "autoWidth": true },
{ "data": "dtFechaRegistro", "autoWidth": true },
{ "data": "nFacturaProveedoresID", "width": "20px", "render": function (data) {
return '<a class="popup" href="/Facturas/Save/' + data + '">Editar</a>';
}
},
{
"data": "EmployeeID", "width": "50px", "render": function (data)
{
return '<a class="popup" href="/Facturas/Delete' + data + '">Borrar</a>';
}
}
]
})
$('.tablecontainer').on('click', 'a.popup', function (e) {
e.preventDefault();
OpenPopup($(this).attr('href'));
})
function OpenPopup(pageUrl) {
debugger;
var $pageContent = $('<div/>');
$pageContent.load(pageUrl, function () {
$('#popupForm', $pageContent).removeData('validator');
$('#popupForm', $pageContent).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('form');
});
$dialog = $('<div class="popupWindow" style="overflow:auto"></div>')
.html($pageContent)
.dialog({
draggable: true,
autoOpen: false,
resizable: true,
model: true,
title: 'ActualizaciĆ³n de Datos',
height: 850,
width: 1650,
close: function () {
$dialog.dialog('destroy').remove();
}
})
debugger;
$('.popupWindow').on('submit', '#popupForm', function (e) {
var url = $('#popupForm')[0].action;
$.ajax({
type: "POST",
url: url,
data: $('#popupForm').serialize(),
success: function (data) {
if (data.status) {
$dialog.dialog('close');
oTable.ajax.reload();
}
}
})
e.preventDefault();
})
$dialog.dialog('open');
}
})
My Controller
public ActionResult GetEmployees()
{
try
{
int proveedor = Convert.ToInt32(Session["IdProveedor"]);
DataSet ConsultaGrid = new DataSet();
ConsultasProveedores ConsultaFacturas = new ConsultasProveedores();
ConsultaGrid = ConsultaFacturas.ConsultaGen(Convert.ToString(proveedor));
List<string> list = new List<string>();
list.Add(ConsultaGrid.Tables[0].Rows[0]["nFacturaProveedoresID"].ToString());
list.Add(ConsultaGrid.Tables[0].Rows[0]["nSiniestroid"].ToString());
list.Add(ConsultaGrid.Tables[0].Rows[0]["cSerie"].ToString());
list.Add(ConsultaGrid.Tables[0].Rows[0]["cFolio"].ToString());
list.Add(ConsultaGrid.Tables[0].Rows[0]["dtFechaFactura"].ToString());
list.Add(ConsultaGrid.Tables[0].Rows[0]["cConcepto"].ToString());
list.Add(ConsultaGrid.Tables[0].Rows[0]["mTotal"].ToString());
list.Add(ConsultaGrid.Tables[0].Rows[0]["dtFechaRegistro"].ToString());
return Json(new
{
data = list
}, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return View("Login");
}
}
You are returning a list of strings (one item per colum). Datatable will expect an array of objects with each object has the defined columns:
"columns": [
{ "data": "nFacturaProveedoresID", "autoWidth": true },
{ "data": "nSiniestroid", "autoWidth": true },
and so on
Your controller should return something like List<Proveedor> where proveedor is:
public class Proveedor {
public int nFacturaProveedoresID {get; set; }
public int nSiniestroid {get; set;}
etc
}
your controller should be like:
public ActionResult GetEmployees()
{
try
{
int proveedor = Convert.ToInt32(Session["IdProveedor"]);
DataSet ConsultaGrid = new DataSet();
ConsultasProveedores ConsultaFacturas = new ConsultasProveedores();
ConsultaGrid = ConsultaFacturas.ConsultaGen(Convert.ToString(proveedor));
List<Proveedor> list = new List<Proveedor>();
list.Add(new Proveedor {
nFacturaProveedoresID = (int)ConsultaGrid.Tables[0].Rows[0]["nFacturaProveedoresID"],
nSiniestroid = (int)ConsultaGrid.Tables[0].Rows[0]["nSiniestroid"],
//rest of fields
});
return Json(new
{
data = list
}, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return View("Login");
}
}

Call function after DataTable is filtered

I have DataTable filled with js-switches, here's the code:
$('#bandsTable').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
'type': 'GET',
'url': 'myUrl',
'data': function (d) {
d._token = Laravel.csrfToken;
}
},
columns: [
{
title: "Number",
data: "number"
},
{
title: "Privileged",
data: "privileged"
}
],
columnDefs: [
{
render: function (data) {
var checked = data ? 'checked' : '';
return '' +
'<input type="checkbox" class="js-switch" id="schedule_deactivation" ' +
checked + ' data-switchery="false" style="display: none;"> \n';
},
targets: 1
}
],
order: [[0, 'asc']],
fnRowCallback: function( nRow, aData, iDisplayIndex ) {
nRow.className = "band-row";
nRow.setAttribute("data-band", aData.number);
return nRow;
},
responsive: true
});
When I filter result's they're displayed correctly, but I don't see checkboxes generated, I can type JS from the console and it works when I type:
var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
elems.forEach(function (html) {
var switchery = new Switchery(html, {
color: '#26B99A',
secondaryColor: '#ff7a77'
});
});
but I don't know when I should call this code. I have no idea about DataTable lifecycle and where should I inject the code. Should it be some callback defined by DataTables or something else?
please see the documentation on the below link for more, but the code should work as follows:
$('#bandsTable').on('draw.dt', function () {
var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
elems.forEach(function (html) {
var switchery = new Switchery(html, {
color: '#26B99A',
secondaryColor: '#ff7a77'
});
});
});
Link:
https://datatables.net/reference/event/

Refresh / Redraw Datatables over function

and i call the datatable over the function.
Here is my function :
function drawTable(yearParameter) {
var oTable = $('#horizontal-monthly').DataTable({
processing: true,
serverSide: true,
ajax: {
url : '{!! route('adm1n.laporan-bulanan-data') !!}',
data : function (d) {
d.year = yearParameter;
}
},
columns: [
{ data: 'B_01', name: 'B_01', sortable: false },
{ data: 'B_02', name: 'B_02', sortable: false }
],
dom : '<"dt-panelmenu clearfix"lr>t<"dt-panelfooter clearfix"ip>',
});
}
And i have event change to call my function above and pass parameter on it.
How to reload the datatables? Cause right now datatables won't reload.
I try to use :
oTable.destroy();
oTable.draw();
It make datatables functionality not work. Like search, pagination etc.
Edit
Here is my change event :
$('#year-value').on('change', function(e) {
var yearParam = $('#year-value').val();
drawTable(yearParam);
});
How to handle that?
Thank you??
Please try
oTable.clear();
oTable.draw();
Also, can I see your change event? I can help you re-add the rows
UPDATE 2
Ok, you can't call DT constructor more than once. First thing what you want to do is to save DT object as global object.
function drawTable() {
if(!oTable)
{
oTable = $('#horizontal-monthly').DataTable({
processing: true,
serverSide: true,
ajax: {
url : '{!! route('adm1n.laporan-bulanan-data') !!}',
data : function (d) {
d.year = filterYearParam;
}
},
columns: [
{ data: 'B_01', name: 'B_01', sortable: false },
{ data: 'B_02', name: 'B_02', sortable: false }
],
dom : '<"dt-panelmenu clearfix"lr>t<"dt-panelfooter clearfix"ip>',
});
}
}
else
{
oTable.ajax.reload().draw();
}
$('#year-value').on('change', function(e) {
filterYearParam = $('#year-value').val();
drawTable();
});
Try this, and then I can try making your year to work.

Categories

Resources