Using fnReloadAjax Still not working - ajax

Using Datatables, and the fnReloadAjax plugin (see below), I am trying to reload the table's data from a server-side script using the following code:
$.fn.dataTableExt.oApi.fnReloadAjax = function(oSettings, sNewSource, fnCallback, bStandingRedraw) {
if (sNewSource !== undefined && sNewSource !== null) {
oSettings.sAjaxSource = sNewSource;
}
// Server-side processing should just call fnDraw
if (oSettings.oFeatures.bServerSide) {
this.fnDraw();
return;
}
this.oApi._fnProcessingDisplay(oSettings, true);
var that = this;
var iStart = oSettings._iDisplayStart;
var aData = [];
this.oApi._fnServerParams(oSettings, aData);
oSettings.fnServerData.call(oSettings.oInstance, oSettings.sAjaxSource, aData, function(json) {
/* Clear the old information from the table */
that.oApi._fnClearTable(oSettings);
/* Got the data - add it to the table */
var aData = (oSettings.sAjaxDataProp !== "") ?
that.oApi._fnGetObjectDataFn(oSettings.sAjaxDataProp)(json) : json;
for (var i = 0; i < aData.length; i++) {
that.oApi._fnAddData(oSettings, aData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
that.fnDraw();
if (bStandingRedraw === true) {
oSettings._iDisplayStart = iStart;
that.oApi._fnCalculateEnd(oSettings);
that.fnDraw(false);
}
that.oApi._fnProcessingDisplay(oSettings, false);
/* Callback user function - for event handlers etc */
if (typeof fnCallback == 'function' && fnCallback !== null) {
fnCallback(oSettings);
}
}, oSettings);
};
$(document).ready(function() {
$('#reloadDataBtn').click(function() {
$('#myTable').fnReloadAjax('mySource2.php');
});
$("#myTable").dataTable({ bSort: true,
"bProcessing": true,
"sAjaxSource": 'mySource1.php',
bAutoWidth: true,
"iDisplayLength": 5, "aLengthMenu": [5, 10, 25, 50, 100],
"sPaginationType": "full_numbers",
"aoColumnDefs": [{ "bSortable": false, "aTargets": [-1, 0]}]
});
});
But I still get the fnReloadAjax is not a function JS error. What am I doing wrong?

In verstion 1.10 of DataTable plugin, function fnReloadAjax is deprecated, now you need use api().ajax.reload() instead:
$(document).ready(function() {
var datatable = $('#calls_list_table').dataTable({
"iDisplayLength": 10,
"processing": true,
"serverSide": true,
"ajax": {
"url": "/calls/data/",
"type": "POST"
}
});
$('button').click(function() {
// use it instead of fnReloadAjax
datatable.api().ajax.reload();
});
});

This is because you address an element returned by jQuery, not the dataTable object itself.
Do this instead :
var dataTable; //reference to your dataTable
$('#reloadDataBtn').click(function() {
dataTable.fnReloadAjax('mySource2.php');
//NOT
//$('#myTable').fnReloadAjax('mySource2.php');
});
dataTable = $("#myTable").dataTable({
bSort: true,
"bProcessing": true,
"sAjaxSource": 'mySource1.php',
bAutoWidth: true,
"iDisplayLength": 5, "aLengthMenu": [5, 10, 25, 50, 100],
"sPaginationType": "full_numbers",
"aoColumnDefs": [{ "bSortable": false, "aTargets": [-1, 0]}]
});
Now fnReloadAjax() will be called proplerly.

Related

how create dynamic multiple jqgrid some page

hi i want create dynamic multiple jqgrid .but create one jqgrid
fisrt dynamic this down html
<div dir='rtl' align='center' class='table - responsive'><div class='row well'>
<table id='dataArray' cellpadding='0' cellspacing='0'></table>
<div id="pager_dataArray"></div>
</div>
</div>
<br />
<div dir='rtl' align='center' class='table - responsive'>
<div class='row well'>
<table id='dataArray2' cellpadding='0' cellspacing='0'></table>
<div id="pager_dataArray2"></div>
</div>
</div>
then use js code for create jqgrid ;plase pay attention iam for get model and header grid call function in js file,
LoadGrid()
data: LoadGrid(),
colNames: getColNames(LoadGrid()[0]),
colModel: getColModels(LoadGrid()[0]),
var searchOptions = ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'bw', 'bn', 'in', 'ni', 'ew', 'en', 'cn', 'nc'];
$(document).ready(function () {
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var today = d.getFullYear() + '/' +
(('' + month).length < 2 ? '0' : '') + month + '/' +
(('' + day).length < 2 ? '0' : '') + day;
$("#dynamicGrouping").change(function () {
var groupingName = $(this).val();
alert(groupingName)
if (groupingName) {
//$('#list').jqGrid('groupingGroupBy', ['AddDate_D', 'Name_c']);
$('#' + gridid).jqGrid('groupingGroupBy', [groupingName]);
} else {
$('#' + gridid).jqGrid('groupingRemove');
}
});
caption: "تست گرید",
$('#' + gridid).jqGrid({
caption: "تست گرید",
//url from wich data should be requested
// url: '#Url.Action("GetProducts","Home")',
datatype: 'local',
//این تابع از فایل androidfunction فراخوانی می شود
data: LoadGrid(),
colNames: getColNames(LoadGrid()[0]),
colModel: getColModels(LoadGrid()[0]),
jsonReader: {
root: "Rows",
page: "Page",
total: "Total",
records: "Records",
repeatitems: true,
userdata: "UserData",
id: "Id",
cell: "RowCells"
},
grouping: true,
iconSet: "glyphIcon",
groupingView: {
// groupField: ['AddDate_D' , 'Name_c'],
groupColumnShow: [true],
groupText: ['<b>{0}</b>'],
groupCollapse: true,
groupOrder: ['asc'],
groupSummary: [true]
},
cmTemplate: { editable: false, autoResizable: true },
toppager: true,
// groupingView: { groupField: ['AddDate_D'] },
mtype: 'POST',
footerrow: true,
// userDataOnFooter : true,
//gridComplete: function () {
// var $grid = $("#FooTable");
// var colSum = $grid.jqGrid('getCol', 'Price_Num', false, 'sum');
// $grid.jqGrid('footerData', 'set', { price: colSum });
//},
pager: $('#' + pagegrid),
//number of rows per page
rowNum: 10,
rowList: [10, 20, 50, 100],
//initial sorting column
sortname: 'Id',
//initial sorting direction
sortorder: 'asc',
// loadonce: true,
shrinkToFit: true,
//we want to display total records count
viewrecords: true,
width: 'auto',
height: 'auto',
hidegrid: false,
direction: "rtl",
gridview: true,
altRows: true,
rownumbers: true,
autoencode: true,
treeGrid: true,
treeGridModel: 'adjacency',
ExpandColClick: true,
// ignoreCase: true,
//loadComplete : function() {
// var table = this;
// setTimeout(function(){
// updatePagerIcons(table);
// }, 0);
//},
loadComplete: function () {
sumarValores($(this))
},
loadError: function (xhr, st, err) {
jQuery("#rsperror").html("Type: " + st + "; Response: " + xhr.status + " " + xhr.statusText);
},
})
.navGrid(
$('#' + pagegrid),
//enabling buttons
{ add: false, del: false, edit: false, search: false },
//edit option
{
width: 'auto', checkOnUpdate: true, checkOnSubmit: true,
beforeShowForm: function (form) {
centerDialog(form, $('#' + gridid));
}
},
//add options
{
width: 'auto', url: '#Url.Action("AddProduct","Home")',
},
//add options
//delete options
{
url: '#Url.Action("DeleteProduct","Home")', reloadAfterSubmit: false
})
.jqGrid('inlineNav', $('#' + pagegrid),
{
// cloneToTop: true,
edit: false, add: true, save: false, cancel: false,
edittext: "ویرایش", addtext: "جدید", savetext: "ذخیره", canceltext: "لغو",
addParams: {
// اگر می‌خواهید ردیف‌های جدید در ابتدا ظاهر شوند، این سطر را حذف کنید
position: "first", //ردیف‌های جدید در آخر ظاهر می‌شوند
rowID: '_empty',
useDefValues: true,
addRowParams: getInlineNavParams(true)
},
editParams: getInlineNavParams(false)
}
)
$('#' + gridid).jqGrid('navButtonAdd', '#list_toppager',
{
caption: ""/*"Show"*/, buttonicon: "ui-icon-extlink", title: "Show Link",
onClickButton: function () {
var grid = $('#' + gridid);
var rowid = grid.jqGrid('getGridParam', 'selrow');
window.location = grid.jqGrid('getCell', rowid, 'dataUrl');
}
});
$('#' + gridid).jqGrid('filterToolbar', {
stringResult: true,//// وجود این سطر سبب می‌شود تا اپراتورها به سرور ارسال شوند
enableClear: false,
searchOnEnter: true,
searchOperators: true, // فعال سازی منوی اپراتورها
defaultSearch: "cn"
});
function getSelectedRow() {
var grid = $('#' + gridid);
var rowKey = grid.jqGrid('getGridParam', "selrow");
if (rowKey)
alert("Selected row primary key is: " + rowKey);
else
alert("No rows are selected");
}
});
function sumarValores($self) {
var sumaHa = 0;
var columnNames = $('#' + gridid).jqGrid('getGridParam', 'colNames');
var global;
var footer = {};
for (var z = 0; z < columnNames.length; z++) {
var colN = columnNames[z];
// $self.jqGrid("footerData", "set", footer);
if (colN == "Price") {
colN = colN.concat('_Num');
var sumtotal = $self.jqGrid("getCol", colN, false, "sum");
// global = colN;
global = 'Price_Num';
footer[global] = sumtotal;
//$self.jqGrid("footerData", "set", {
// Price_Num: sumtotal,
//});
$self.jqGrid("footerData", "set", footer);
break;
}
if (colN == "AddDate") {
global = 'AddDate_D';
var sumtotald = $self.jqGrid("getCol", colN, false, "sum");
// footer[global] = sumtotald;
$self.jqGrid("footerData", "set",
{
AddDate_D: sumtotald,
}
);
}
}
}
function getInlineNavParams(isAdd) {
return {
// استفاده از آدرس‌های مختلف برای حالات ویرایش و ثبت اطلاعات جدید
url: isAdd ? '#Url.Action("AddUser", "Home")' : '#Url.Action("EditUser","Home")',
key: true,
restoreAfterError: false, // این مورد سبب می‌شود تا اعتبارسنجی سمت سرور قابل اعمال شود
oneditfunc: function (rowId) {
// نمایش دکمه‌های ذخیره و لغو داخل همان سطر
$("#jSaveButton_" + rowId).show();
$("#jCancelButton_" + rowId).show();
},
successfunc: function () {
var $self = $(this);
setTimeout(function () {
$self.trigger("reloadGrid"); // دریافت کلید اصلی ردیف از سرور
}, 50);
},
errorfunc: function (rowid, response, stat) {
if (stat != 'error') // this.Response.StatusCode == 200
return;
var result = $.parseJSON(response.responseText);
if (result.success === false) {
//نمایش خطای اعتبار سنجی سمت سرور پس از ویرایش یا افزودن
$.jgrid.info_dialog($.jgrid.errors.errcap,
'<div class="ui-state-error">' + result.message + '</div>',
$.jgrid.edit.bClose,
{ buttonalign: 'center' });
}
}
};
}
function centerDialog(form, grid) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
}
function getColNames(data, status) {
var keys = [];
if (status != 'headr') {
for (var key in data) {
if (data.hasOwnProperty(key)) {
keys.push((key.split('_'))[0]);
}
}
keys.push('');
}
else {
for (var key in data) {
if (data.hasOwnProperty(key)) {
keys.push(key);
}
}
keys.push('');
}
return keys;
}
function getColModels(data) {
var colNames = getColNames(data, 'headr');
var colModelsArray = [];
for (var i = 0; i < colNames.length; i++) {
var str;
if (i === 0) {
str = {
name: (colNames[i]),
index: (colNames[i]),
key: true,
editable: false,
search: false,
width: 20,
};
} else if (i >= 1 && i <= colNames.length - 2) {
switch ((colNames[i].split('_'))[1]) {
case ('Num'):
str = {
name: (colNames[i]),
index: (colNames[i]),
editable: true,
summaryType: 'sum', summaryTpl: '<b>جمع مشاهدات: {0}</b>',
//width: 100,
searchoptions: { sopt: searchOptions },
formatter: 'currency',
formatoptions:
{
decimalSeparator: '.',
thousandsSeparator: ',',
decimalPlaces: 0,
prefix: 'ريال'
},
editable: true, edittype: 'text',
// summaryType: function (val, name, record) {
};
// tt = 'Price_Num';
break;
case ('D'):
str = {
name: (colNames[i]),
index: (colNames[i]),
editable: true,
// width: 100,
searchoptions: {
dataInit: function (elem) {
$(elem).datepicker({
dateFormat: 'm/d/y',
onClose: function (event) {
$('#' + gridid).trigger("reloadGrid", [{ page: 1 }]);
}
});
// datepicker({
// dateFormat: 'dd/mm/yy',
// changeYear: true,
// changeMonth: true,
// showWeek: true,
// onSelect: function (dateText, inst) {
// setTimeout(function () {
// $('#' + gridid)[0].triggerToolbar();
// }, 100);
// }
//});
},
dataInit: function (elem) {
$(elem).datepicker({
dateFormat: 'm/d/y',
onClose: function (event) {
$('#' + gridid).trigger("reloadGrid", [{ page: 2 }]);
}
});
}
, sopt: searchOptions
},
editoptions: {
maxlength: 10,
onclick: 'PersianDatePicker.Show(this,' + '1395/02/01' + ')'
},
editrules: {
required: true
}
};
break;
case ('c'):
str = {
name: (colNames[i]),
index: (colNames[i]),
editable: true,
//width:100,
searchoptions: { sopt: searchOptions },
};
break;
default:
// alert('>41');
}
}
else {
str = {
name: 'myac',
index: colNames[i],
resize: false,
fixed: true, sortable: false,
formatter: 'actions',
search: false,
formatoptions: {
keys: true
},
}
}
//formatter: 'currency',
//formatoptions:
//{
// decimalSeparator: '.',
// thousandsSeparator: ',',
// decimalPlaces: 2,
// prefix: '$'
//},
//editable: true, edittype: 'text',
colModelsArray.push(str);
}
return colModelsArray;
}
function updatePagerIcons(table) {
//var replacement =
//{
// 'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
// 'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
// 'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
// 'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
//};
//$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
// var icon = $(this);
// var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
// if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
//})
}
$(document).ready(function () {
function LoadGrid() {
object = {
"dataArray":
[
{ id_R: 1, Name_c: "dummy1", AddDate_D: "1394/07/27", Price_Num: "10000" },
{ id_R: 2, Name_c: "dummy2", AddDate_D: "1394/07/28", Price_Num: "120000" },
],
"dataArray2":
[
{ id_R: 9, Name2_c: "dummy9", AddDate2_D: "1393/04/28", Price2_Num: "200000" },
{ id_R: 10, Name_c: "dummy10", AddDate_D: "1393/04/04", Price_Num: "2100000" },
]
};
// برای مپ کردن ارایه یه ارایه دیگر
//departement = $.map(dataArray, function (value, index) {
// return [value];
//});
var names = Object.getOwnPropertyNames(object);
// var names = 'grd1'
var col = [];
var gridarr = [];
var pagegrarr = [];
//مقادیر ارایه را در متغیر زیر می ریزد
var col = Object.values(object);
//تعداد ارایه برای گرید بدست اوردیم
var countarr = col.length;
for (var i = 0; i < countarr; i++) {
//اسم جدول گرید
gridarr[i] = names[i];
pagegrarr[i] = 'pager_' + names[i];
// return col[i];
}
flag++;
switch (flag) {
case 1:
case 2:
case 3:
case 4:
gridid = gridarr[0]
pagegrid = pagegrarr[0]
return col[0];
break;
case 5:
case 6:
case 7:
case 8:
gridid = gridarr[1]
pagegrid = pagegrarr[1]
return col[1];
break;
default:
break;
}
}
});
this answer:
<script>
$(document).ready(function () {
function grid(tt) {
//=== LOCA VARIABLES ===//$.jgrid.randId()
var myGrid = $("<table>").attr("id", tt);
var myPager = $("<div>").attr("id", tt +"_pager");
var localData1 = {
"page": 1,
"totalRecords": 5,
"pageSize": 3,
"rows": [
{ Name: "Name 1" },
{ Name: "Name 3" },
{ Name: "Name 2" }
]
};
function publicInit() {
$("body").append(myGrid, myPager);
myGrid.jqGrid({
pager: myPager,
data: localData1.rows,
datatype: "local",
colModel: [
{ name: 'Name', index: 'Name', width: "500" }
],
//localReader: {
// repeatitems: false
// },
// rowNum: 3,
viewrecords: true,
height: "auto",
ignoreCase: true
});
}
//=== REVEALING PATTERN===//
return {
init: publicInit
}
};
var grid1 = new grid("y");
grid1.init();
$("body").append("<br><br>"); //Add some spacing to distinguish between both grids
var grid2 = new grid("c");
grid2.init();
$("body").append("<br><br>"); //Add some spacing to distinguish between both grids
var grid2 = new grid("b");
grid2.init();
});
</script>

datatable yadcf plugin init() not working

i am using datatable with bootstrap3. i want to apply filter after button is clicked. but when i clicked button it gives me TypeError: oTable.settings is not a function error. my datatable version is 1.10.6 and yadcf version is 0.8.7
here is my code
function init_datatable(table_id, records) {
// console.log('init table',$.parseJSON(records));
var oTable = $(table_id).dataTable({
aaData: $.parseJSON(records),
"sPaginationType": "bootstrap",
"bFilter": false,
"bInfo": false,
"sPageButtonActive": "active",
"aaSorting": [[0, 'desc']],
"bDeferRender": true,
"sDom": '<"top"if>rt<"bottom"lp><"clear">',
"aLengthMenu": [
[10, 20, 30, 50, -1],
[10, 20, 30, 50, "All"] // change per page values here
],
"iDisplayLength": 10,
"oLanguage": {
"sEmptyTable": "No data available"
},
"aoColumnDefs": [{
"aTargets": [0],
"bVisible": false,
"bSearchable": false
},
{
"bSortable": false,
"aTargets": [-1], // <-- gets last column and turns off sorting
"mData": null,
"mRender": function(data, type, full) {
return '<a data-original-title="Edit" id="edit_' + full[0] + '" data-placement="top" class="btn btn-xs btn-teal tooltips edit" href="javascript:void(0)"><i class="fa fa-edit"></i> Edit</a>';
}
}]
});
// .yadcf([
// {column_number: 1}
// ]);
$(table_id + '_wrapper .dataTables_length select').addClass("m-wrap");
$(table_id + '_wrapper .dataTables_length select').select2();
return oTable;
}
here is code for apply column filter
var pTable = init_datatable('#tbl_sample', data);
function apply_column_filter() {
yadcf.init(pTable, [
{column_number: 1}
]);
}
commented code in "init_datatble function is working. but when i use init it gives me error
yadcf.init should be use only for the new API with the capital D and since you are not using the new API, you should use the following way to init yadcf
$(table_id).dataTable({
......
}).yadcf([......]);
See comments in the code snippets on the showcase
//----------------------------------------------
//Example on how to define a custom filter function
//this function is goinf to be passesd to yadcf as custom_func parameter value
//and going to be tested against each value in the column
//----------------------------------------------
b.t.w if you want to filter some column pragmatically you should use the
exFilterColumn function , see docs
You can still use "yadcf.init" by getting the table reference. And this is how can get the reference of a table:
var api = new jQuery.fn.dataTable.Api(settings);
var oTable = api.table();
yadcf.init(oTable, [ {}]);

Is it possible for pagination last button reload in jquery datatable?

Is it possible for pagination last button reload in jquery datatable?
I have used jquery datable ,Now my record more than one lack's data.
So I have page initialize 1000 record load and then last pagination button click reload data 1000.
can give me any other idea...?
For your reference:
$("#tblExmaple").hide();
jQuery(document).ready(function ($) {
getRecords();
function getRecords() {
jQuery.support.cors = true;
$.ajax({
cache: false,
type: "GET",
url: "http://localhost:1111/TestSample/api/getRecords",
datatype: "json",
data: { Arg1: "Values1",Arg2: "Values2",Arg2: "Values3" },
statusCode: {
200: function (data) {
$.each(data, function (index, obj) {
var colRes1 = obj.Res1;
var colRes2 = obj.Res2;
var dataAdd = [colRes1, colRes2];
getData.push(dataAdd);
});
// Server Side Code
setTimeout(function () {
$('#tblExmaple').dataTable({
"sPaginationType": "full_numbers",
"sScrollXInner": "50%",
"sScrollyInner": "110%",
"aaData": getData,
"iDisplayLength": 8,
"sInfoEmpty": false,
"bLengthChange": false,
"aoColumns": [
{ "sTitle": "Column1" },
{ "sTitle": "Column2" }
];
})
}, 500);
setTimeout(function () {
$("#tblExmaple").show();
}, 500);
},
408: function (data) {
var response_Text = JSON.stringify(data, undefined, 50);
if (data.response_Text == undefined) {
window.location = "/Home/Index";
}
else {
timeoutClear();
}
}
}
});
}

Using Jquery Datatables plugin with MVC 3?

I have 2 filter text boxes:
How do I pass these values to my controller below? How do I access them from controller "GetAgencies()"?
Client Side code:
$(document).ready(function () {
$('#agencyList').dataTable({
"bServerSide": true,
"sAjaxSource": "GetAgencies",
"bProcessing": true,
"iDisplayLength": 10,
"bLengthChange": false,
"bFilter": false,
"aoColumns": [
{ "sName": "Agency_Ori",
"bSearchable": false,
"bSortable": false,
"fnRender": function (oObj) {
return '<a href=\"Details/' +
oObj.aData[0] + '\">' + oObj.aData[0] +'</a>';
}
},
{ "sName": "Agency_Name" },
{ "sName": "COPSAuditNumber" },
{ "sName": "OIGAuditNumber" }
]
});
});
</script>
Controller:
public ActionResult GetAgencies(jQueryDataTableParamModel param)
{
AuditDAL ad = new AuditDAL();
var agencies = ad.SearchAgencies("Ak001", "");
string col = param.sColumns.Split(',')[param.iSortCol_0];
string orderby = col + " " + param.sSortDir_0;
IEnumerable<AuditAgency> filteredAgencies = agencies;
var results = filteredAgencies
.Skip(param.iDisplayStart)
.Take(param.iDisplayLength);
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = agencies.Count(),
iTotalDisplayRecords = filteredAgencies.Count(),
aaData = (
from n in results
select new[]
{
n.Agency_Ori,
n.Agency_Name,
n.COPSAuditNumber,
n.OIGAuditNumber
}).ToArray()
},
JsonRequestBehavior.AllowGet);
}

Jqgrid - Multiselectected rows no longer persist after triggering a JqGrid reload

I have a multi-selected Jqgrid. Initially on loading the grid with the Json reponse from the server, the multiselected rows persist correctly as I navigate from one page to another.
The ids of the rows selected are stored in an Array and this Array is updated on paging. I use this array to check the already selected rows on returning back to the page. Sorting works fine and I faced no problem so far.
On applying a filter on a particular field, a request is sent to the server which returns the new filtered result in Json and then reloads the grid with it.
The first page is rendered correctly with the selected rows checked but on changing the page and returning back the rows are no longer selected. However the array still contains the ids and is also containing the new added ids.
How is that the Multiselected feature stops working after a reload??? Or is it not even because of the reload??
Here is the code:
<script type='text/javascript'>
var selectedFieldsMap={};
var selectedFieldsObjs = [];
var selectedFieldIds = [];
$(function() {
//function called when applying a filter
$('#ApplyFilterBtn').click(function() {
saveGridState();
$('#Grid').setGridParam({ url: getUrl() });
$('#Grid').trigger('reloadGrid');
});
});
function saveGridState() {
var selectedIds = $('#Grid').getGridParam('selarrrow');
$('#Grid').data(current_page, selectedIds);
_.each(selectedIds, function(id) {
selectedFieldIds.push(id);
});
var idsToBeAdded = _.difference(selectedIds, getExistingRowIdsForGrid('#list'));
selectedFieldsMap[current_page] = idsToBeAdded;
_.each(idsToBeAdded, function(id) {
selectedFieldsObjs.push($('#Grid').getRowData(id));
});
}
function getExistingRowIdsForGrid(gridSelector) {
var existingFields = $(gridSelector).getRowData();
return _.map(existingFields, function(obj) { return obj.Id; });
function resetFilterValuesAndReloadGrid() {
//reset filters and set grid param
$('#Grid').setGridParam({
sortname: 'Id',
sortorder: 'asc',
page: 1,
url: getUrl()
});
$('#Grid').jqGrid('sortGrid', 'Id', true);
$("#Grid").trigger('reloadGrid');
}
$("#Grid").jqGrid({
url: getUrl(),
datatype: "json",
edit: false,
add: false,
del: false,
height: 330,
mtype: 'GET',
colNames: ['Id', 'Type', 'Category'],
jsonReader: {
root: "DataRoot",
page: "CurrentPage",
total: "TotalPages",
records: "TotalRecords",
repeatitems: false,
cell: "",
id: "0"
},
colModel: [
{ name: 'Id', index: 'Id', width: 95, align: 'center', sorttype: "int" },
{ name: 'Type', index: 'ValueTypeName', width: 110, align: 'left',sortable: true },
{ name: 'Category', index: 'Category', width: 72, align: 'left', sortable: true },
],
pager: '#pager',
rowNum: pageCount[0],
rowList: pageCount,
sortname: 'Id',
sortorder: 'asc',
viewrecords: true,
gridview: true,
multiselect: true,
loadComplete: function () {
if(selectedFieldIds) {
$.each(_.uniq(selectedFieldIds), function(index, value) {
$('#Grid').setSelection(value, true);
});
}
} ,
onPaging : function () {
saveGridState();
},
loadBeforeSend: function() {
current_page = $(this).getGridParam('page').toString();
} ,
onSortCol: function () {
saveGridState();
}
});
}
function getUrl() {
//return url with the parameters and filtering
}
</script>
The problem is solved, what happens is on reload of the grid the function which checks the row is called as it is in the document.ready()and the on grid loadComplete the same function is called. Toggle happens and the selection is removed. I've added an if condition to see if the grid is selected or not.
loadComplete: function () {
var selRowIds = jQuery('#Grid').jqGrid('getGridParam', 'selarrrow');
if (selRowIds.length > 0) {
return false;
} else {
var $this = $(this), i, count;
for (i = 0, count = idsOfSelectedRows.length; i < count; i++) {
$this.jqGrid('setSelection', idsOfSelectedRows[i], false);
}
}
}

Resources