Pagination in Jquery Datatable in asp.net webforms - javascript

I have an API, which accepts page number and page size as a parameter to return user details.
Loading data to the jquery data table. Needs to pass page number and size to API for fetch the data each time. How can I get and pass the page number to webmethod and enable next button all time. Because when i loaded first time data it only shows page number as 1 and Next button is disabled.
var tableUserDetails = $("#grdUser").DataTable({
processing: true,
filter: true,
orderMulti: false,
paging: true,
searching: true,
bFilter: true,
bsort: true,
bInfo: true,
pagingType: "simple",
columns: [{ "data": "Id" },
{ "data": "Name" },
{ "data": "userName" },
{ "data": "email" },
{ "data": "role" }
]
});
function getUsers() {
var info =tableUserDetails.page.info();
$.ajax({
data: '{pageNumber:' + info.page+1 + ', pageSize:' + 10 + '}',
type: "POST",
url: "MyPage.aspx/GetUsers",
contentType: Constants.ContentType,
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
},
});
}

I think that you are looking for this: DataTables server side processing. The configuration you have is not loading partially the data. It assumes you have all the rows when you set the dataset.
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
} );
} );
And the format of the returned data should be like this:
{
"draw": 3,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
[
"Airi",
"Satou",
"Accountant",
"Tokyo",
"28th Nov 08",
"$162,700"
],
/* etc */
An example of C# like response:
/// <summary>
/// Resultset to be JSON stringified and set back to client.
/// </summary>
[Serializable]
[SuppressMessage("ReSharper", "InconsistentNaming")]
public class DataTableResultSet
{
/// <summary>Array of records. Each element of the array is itself an array of columns</summary>
public List<List<string>> data = new List<List<string>>();
/// <summary>value of draw parameter sent by client</summary>
public int draw;
/// <summary>filtered record count</summary>
public int recordsFiltered;
/// <summary>total record count in resultset</summary>
public int recordsTotal;
public string ToJSON()
{
return JsonConvert.SerializeObject(this);
}
}
Edit - How to post with ajax
$(document).ready(function () {
$('#mytable').DataTable({
processing: true,
serverSide: true,
ajax: {
data: '{pageNumber:' + info.page+1 + ', pageSize:' + 10 + '}',
type: "POST",
url: "MyPage.aspx/GetUsers",
contentType: Constants.ContentType,
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
}
});
});

Related

jqGrid filterToolbar only works with some columns

When I try searching for the string Test in the column "Erstellt Von", I get no results. There's no error in the console either.
This is the codepart I used:
var colUserTemplate = {
width: 160, align: 'left',
formatter: function (cellvalue, options, rowObject) {
return "Test";
}
}
In another column, the filtering works perfectly fine:
Here's how grids are loaded and the filterToolbar:
function loadGrid(listname, query, divname, colnames, colmdodel, showFilter, showExcelExport) {
$("#" + divname).jqGrid({
datatype: function () { loadGridData(listname, query, divname); },
colNames: colnames,
colModel: colmdodel,
height: "100%",
loadonce: true,
rowNum: 9999,
gridComplete: function () {
$("#" + divname + "no").html(" [" + $("#" + divname).jqGrid('getGridParam', 'records') + "]");
$("#" + divname).jqGrid('setGridParam', { datatype: 'local' });
},
ondblClickRow: function (rowid, iRow, iCol, e) {
onDoubleClickGrid(rowid, iRow, iCol, e, divname, listname);
}
});
if (showFilter) {
$("#" + divname).jqGrid('filterToolbar', {
autosearch: true,
stringResult: false,
searchOnEnter: true,
defaultSearch: "cn",
});
}
}
I tried using
if (showFilter) {
$("#" + divname).jqGrid('filterToolbar', {
autosearch: true,
stringResult: true,
searchOnEnter: true,
defaultSearch: "cn", ignoreCase: true
});
}
but it didn't change anything.
If you want to have a look, here's the full code.
Been trying to fix this issue for hours, so any help is appreciated!
EDIT:
When writing this:
var thegrid = $("#" + divname)[0];
console.log("data.d.results: " + data.d.results);
thegrid.addJSONData(data.d.results); //Binding data to the grid
console.log("thegrid:" + thegrid.innerHTML);
I get the following result:
Here's the expanded object:
You use a function to load the data:
function loadGridData(listname, query, divname) {
$.ajax({
url: "/tools/AKG/_api/web/lists/getbytitle('" + listname + "')/Items?" + query,
type: "GET",
headers: { "Accept": "application/json;odata=verbose" },
success: function (data, textStatus, xhr) {
var thegrid = $("#" + divname)[0];
thegrid.addJSONData(data.d.results); //Binding data to the grid
},
error: function (xhr, textStatus, errorThrown) {
alert("error:" + JSON.stringify(xhr));
$('#' + divname + 'records').html(" [0]");
}
});
}
In the success function data.d.results contain your grid data. Before to put this data in addJSONData loop over that column and change its value or better do it at server if possible

ajax datatable, cannot retrieve data

I Edited my code, but the problem now is i can't retrieve my data but there is no error in my code, Also i have records in my database. I can't figure it out why my data is not dislaying.
//Controller - where i getting my data in database.
public ActionResult GetEmployeeFlexiSched()
{
string query = "exec spdGetEmployeeFlexiSched";
string strReturn = GlobalFunction.DataTableToJSON(GlobalFunction.TableFromMSSQL(conn, query));
return Json(new { success = true, data = strReturn }, JsonRequestBehavior.AllowGet);
}
<script>
$(document).ready(function () {
var dataTable = $('#OedTB').DataTable({
"language": {
emptyTable: "No Transaction"
},
ajax: {
url: '#Url.Action("GetEmployeeFlexiSched", "FlexiSchedule")',
dataType: "json",
retrieve: "true",
processing: "true",
serverSide: "true",
type: "POST",
dataSrc: "",
},
order: [],
columnDefs: [
{
orderable: false,
}
],
columns: [
{data: "TranNo"},
{data: "FullName"},
{
data: "TranNo",
render: function (data, type, row, meta) {
return '<button type="button" class="btn btm-sm btn-outline-danger viewdetails" id="' + data + '"><i class="fas fa-info-circle"></i></button>';
}
},
]
});
});
</script>

Field name is in JSON but datatables don't recognise it?

The error message is as below:
Requested unknown parameter 'emPONumber' for row 0, column 0
But emPONumber is in the JSON, why datatables still prompt this error?
<script type="text/javascript">
$(document).ready(function () {
var tableId = 'tablePurchaseOrders';
var table = $('#' + tableId).DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: 'http://localhost/ControlTower2WebAPI/api/PurchaseOrder/GetAllUploadedPurchaseOrders',
type: 'GET',
data: function (data) {
//debugger;
var model = {
draw: data.draw,
start: data.start,
length: data.length,
columns: data.columns,
search: data.search,
order: data.order
};
return model;
},
failure: function (result) {
debugger;
alert("Error occurred while trying to get data from server: " + result.sEcho);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
alert("Error occurred while trying to get data from server!");
},
dataSrc: function (json) {
var _data = JSON.stringify(json.Data);
debugger;
return _data;
}
}
,
"columns": [
{ "data": "emPONumber", title: "emPONumber" },
{ "data": "ASMPONumber", title: "ASMPONumber" },
{ "data": "material", title: "material" }
]
});
});
</script>
json in dataSrc: function (json):
{"ContentEncoding":null,"ContentType":null,"Data":{"draw":1,"recordsTotal":1,"recordsFiltered":1,"data":[{"emPONumber":"EM1234567","ASMPONumber":"A741000013","material":"26-00010","quantity":5,"UOM":"EA","asmPOQuantity":5,"createBy":"m","ASMPOYear":2018,"ASMPOMonth":6,"ASMPOVendor":"10008"}]},"JsonRequestBehavior":1,"MaxJsonLength":null,"RecursionLimit":null}
json (_data) return by ajax in dataSrc:
{
"draw":1,
"recordsTotal":1,
"recordsFiltered":1,
"data":
[{
"emPONumber":"EM1234567",
"ASMPONumber":"A741000013",
"material":"26-00010",
"quantity":5,
"UOM":"EA",
"asmPOQuantity":5,
"createBy":"m",
"ASMPOYear":2018,
"ASMPOMonth":6,
"ASMPOVendor":"10008"
}]
}
Try
dataSrc: function (json) {
for(key in json.Data){ json[key] = json.Data[key]; }
delete json['Data'];
return json.data;
}

How to delete a row without Ajax request

Using jQuery DataTables 1.9.4, I simply post row ID to server and when it's deleted from the database and comes back to ajax success() function I use fnDeleteRow() row function to delete this row from the table.
But this triggers fnDraw() function init and makes an Ajax request to the server that is unnecessary.
How can I simply delete this row and arrange table on client side ?
confirmDelete = function()
{
var data = {
"rowid_":rowid
};
$.ajax({
url:"../../Controller/ObjectController.php5",
type:"POST",
dataType: "json",
data: data,
success: function(data) {
debugger
if(data.Success)
{
tableObjects.fnDeleteRow($("#tr_"+rowid),function(){
event.theme ='lime';
event.heading ='<i class=\'fa fa-check\'></i> Process Completed';
event.message ='Row deleted successfully.';
ntf(event);
});
}
here is my taable definition:
var tableObjects = $("#objectTable").DataTable({
"bProcessing": false,
"bServerSide": true,
"sAjaxSource": "../../Controller/ObjectController.php5",
"aoColumns": [
{ "mDataProp": "NAME"},
{ "mDataProp": "TYPE"},
{ "mDataProp": "IP"},
{ "mDataProp": "REMARK"},
{"mDataProp": "btnEdit"},
{"mDataProp": "btnDelete"}
],
"fnServerData": function (sSource, aoData, fnCallback){
aoData.push({"name":"tablename","value":"objects"})
debugger
$.ajax({
"dataType": "json",
"contentType": "application/json; charset=utf-8",
"type": "GET",
"url": sSource,
"data": aoData,
"success": function(result){
policyCount = result["iTotalRecords"];
$.each(result.aaData, function(index,value){
result.aaData[index]["btnEdit"] ="<a id=\"btnEdit\" class=\"btn btn-sm btn-success\" style=\"border-radius:4px\" onclick=\"fillFormwithDatasforEdit('"+value.NAME+"','"+value.REMARK+"','"+value.TYPE+"','"+value.IP+"')\" href=\"#mdlObjects\" data-toggle=\"modal\"><i class=\"fa fa-edit\"></i> Edit </a>";
result.aaData[index]["btnDelete"] ="<a class=\"btn btn-sm btn-danger\" href=\"#basic\" style=\"border-radius:4px\" onclick=\"setModalTitle('"+value.NAME+"','DeleteObject')\" data-toggle=\"modal\"><i class=\"fa fa-trash-o\"></i> Delete </a>";
result.aaData[index]["REMARK"] ="<a class=\"btn btn-sm btn-info\" style=\"border-radius:4px\" onclick=\"setremark('"+value.NAME+"','"+ value.REMARK +"')\" data-toggle=\"modal\" href=\"#full\"><i class=\"fa fa-comment\"></i> Remark</a>";
});
fnCallback(result);
},
error: function (xhr, textStatus, error){
if (typeof console == "object") {
console.log(xhr.status + "," + xhr.responseText + "," + textStatus + "," + error);
}
}});
},
"oLanguage": {
"sLengthMenu": '<select>' +
'<option value="5">5</option>' +
'<option value="10">10</option>' +
'<option value="20">20</option>' +
'<option value="30">30</option>' +
'<option value="40">40</option>' +
'<option value="50">50</option>' +
'</select> Show'
},
"fnCreatedRow": function( nRow, aData, iDataIndex ) {
objectname = aData["NAME"];
newRowID = "tr_" +objectname;
$(nRow).attr('id', newRowID);
$(nRow).find('td').each (function(index) {
newRowID = index==0?objectname+"_objectname":index==1?objectname+ "_type"
:index==2?objectname+"_ipaddress":index==3?objectname+"_btnremark"
:index==4?objectname+ "_btnedit":index==5?objectname+"_btndelete":"";
$(this).attr('id', newRowID);
});
},
"fnDrawCallback": function(){
},
"aaSorting": [
[2, 'asc']
],
"aLengthMenu": [
[5, 15, 20, -1],
[5, 15, 20, "All"] // change per page values here
],
"iDisplayLength": 5
});
Client-side processing mode
In client-side processing mode ("bServerSide": false), fnRowDelete() doesn't trigger Ajax request.
See this JSFiddle for demonstration. Look for Request in the console when the request is made.
Server-side processing mode
However, in server-side processing mode ("bServerSide": true), fnRowDelete() will trigger Ajax request.
Notes
API method fnRowDelete() has a third optional boolean argument that determines whether table should do a redraw. For example:
oTable.fnRowDelete(0, function(){ console.log('Deleted'); }, false);
If re-draw is not request, you would be responsible to re-draw the table yourself later with fnDraw() which also accepts optional boolean argument that determines whether to re-filter and resort the table before the draw. For example:
oTable.fnDraw(false);

Pass complex javascript object configuration(data and functions) from json string

I have a javascript that has a bunch of parameters and functions inside of it.
ctrl.kendoGrid({
dataSource: {
type: "odata",
transport: {
read: {
url: "odata/CodeView",
dataType: "json",
contentType: "application/json"
},
update: {
url: function (data) {
return "api/CodeMapUpdate/" + data.CODE_MAP_ID;
},
dataType: "json",
type: "post",
complete: function (e) {
ctrl.data("kendoGrid").dataSource.read();
if (e.status == 201) {
logger.log("Record Updated: Record ID = " + e.responseJSON, null, null, true);
} else {
logger.logError(" Save failed " + e.responseJSON.ExceptionMessage, null, null, true);
}
}
},
destroy: {
url: function (data) {
return "api/CodeMapDelete/" + data.CODE_MAP_ID;
},
dataType: "json",
complete: function () {
ctrl.data("kendoGrid").dataSource.read();
}
},
create: {
url: "api/CodeMapCreate",
dataType: "json",
complete: function (e) {
ctrl.data("kendoGrid").dataSource.sort({
field: "CODE_MAP_ID",
dir: "desc"
});
ctrl.data("kendoGrid").dataSource.filter({});
if (e.status == 201) {
logger.log("Record Created: Record ID = " + e.responseJSON, null, null, true);
} else {
logger.logError(" Save failed " + e.responseJSON.ExceptionMessage, null, null, true);
}
}
},
},
schema: {
data: function (data) {
return data.value;
},
total: function (data) {
return data["odata.count"];
},
model: {
id: "CODE_MAP_ID",
fields: {
CODE_MAP_ID: {
editable: false,
type: "number"
},
CODE_NAME: {
type: "string",
validation: {
title: "Required Field",
required: true
}
},
L_NAME: {
type: "string",
validation: {
required: true
}
},
CODE_DATE: {
field: "CODE_DATE",
type: "date",
format: "{0:MM/dd/yyyy}",
validation: {
required: true
}
},
}
}
},
change: function () {
},
//batch: true,
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
sort: {
field: "CODE_MAP_ID",
dir: "desc"
}
//autoSync: true
} })
I am trying to save the entire "dataSource" object as a variable and retrieve it at runtime with ajax.
I am able to do this with eval ("(" + dataSource + ")") but any included functions are no longer executing.
Any idea on a strategy to store/retrieve this type of an object to/from JSON?
here is a simple demo of how to use the 2nd param to JSON.parse to recover stored functions:
var ob={a:1, b:false, c: function(a){ return a * a;} };//a sample object
Function.prototype.toJSON=Function.toString; //extend JSON to cover Functions
var str=JSON.stringify(ob, null, "\t"); //turn sample object into a string:
/* str =={
"a": 1,
"b": false,
"c": "function (a){return a*a;}"
} */
//now turn the string back into an object, using a reviver to re-parse methods:
var ob2=JSON.parse(str, function(a,b){
if(b.match && b.match(/^function[\w\W]+\}$/)){ b=eval("b=0||"+b); }
return b;
});
var n=5; //let's try the method using a number
var n2=ob2.c(5); //apply the method to the number
alert(n2); // shows: 25, the number times itself, verifying that the function works
You might want to be a litle stricter about what you send to eval, maybe use a key schema in addition to matching properties that simply look like functions. you can beef-up the regexp to be a little stricter, but for this quick demo of the JSON.parse() parameter, it all works just fine.
In this case, since you are collecting the properties of the JSON, there's no chance of running into the security issues that eval() use can facilitate. Those problems stem from sending one user's input to another user without filtering, not when you jump-start code the client itself produced last time...

Categories

Resources