jqGrid: Searching with json data - spring

I have succeeded to load data from server in spring framework with pagination but my searching/finding records and filter bar is not working.
But if i make loadonce=true then the filter or searching working fine.
My code for my jsp is:
var allColumnNames=["Sr. No","contactName", "city", "country"];
var grid = jQuery('#list');
grid.jqGrid({
url:'customerData.html',
datatype: 'json',
mtype: 'GET',
loadonce: false,
colNames: allColumnNames,
colModel: [
{ name:'id', index:'id', jsonmap:"id", width:20,index:'id', search:true, stype:'int' ,hidden:true},
{ name: "contactName" ,index:'contactName', width:160, search:true, stype:'text' },
{ name: "city",index:'city', width:160, search:true, stype:'text' },
{ name: "country" ,index:'country', width:160, search:true, stype:'text' }
],
caption: 'Customer Details',
height: 'auto',
gridview: true,
rownumbers: true,
viewrecords: true,
pager: '#pager',
rowNum: 10,
rowList: [5, 10, 20, 50],
rownumbers: true
});
$("#search").click(function() {
var searchFiler = $("#filter").val(), f;
if (searchFiler.length === 0) {
grid[0].p.search = false;
$.extend(grid[0].p.postData,{filters:""});
}
f = {groupOp:"OR",rules:[]};
f.rules.push({field:"contactName",op:"cn",data:searchFiler});
f.rules.push({field:"city",op:"cn",data:searchFiler});
grid[0].p.search = true;
$.extend(grid[0].p.postData,{filters:JSON.stringify(f)});
grid.trigger("reloadGrid",[{page:1,current:true}]);
});
I am new to jqGrid, Please help me in above problem.
Thanks in advance!

When you put loadonce=true jqGrid only makes one request that takes all the data, and then if you filter, sort, search... are controlled by jqGrid in the frontend.
But if loadonce=false, only loads the data needed at this moment, and every time jqGrid needs new data, it sends another request to the server with differents parameters.
So I can guess that your server file "customerData.html", it's not ready to answer all the different questions.
Here http://trirand.com there are a lot of jqGrid examples an most of them have the server side code.

Related

Why "allData" is an empty array?

I am trying to get the data from a jqGrid (free version and latest version) and it's suppose that I get:
all the data if none is selected
the selected data if any
This is how I am doing it:
$(function () {
var $order_logs = $('#order_logs');
$order_logs.jqGrid({
url: Routing.generate('api_order_logs'),
datatype: "json",
colModel: $colmodel.data('values'),
width: 980,
height: 300,
pager: true,
toppager: true,
hoverrows: true,
shrinkToFit: true,
autowidth: true,
rownumbers: true,
viewrecords: true,
rowList: [25, 50, 100],
rownumWidth: 60,
gridview: true,
sortable: {
options: {
items: ">th:not(:has(#jqgh_order_logs_cb,#jqgh_order_logs_rn,#jqgh_order_logs_actions),:hidden)"
}
},
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
records: 'records',
cell: '',
repeatitems: false
},
cmTemplate: {autoResizable: true, editable: true},
autoResizing: {compact: true, resetWidthOrg: true},
autoresizeOnLoad: true
}).jqGrid('navGrid', {
edit: false,
add: false,
del: false,
search: false,
refresh: true,
refreshstate: "current",
cloneToTop: true
}).jqGrid('navButtonAdd', {
caption: 'Export',
title: 'Export',
onClickButton: function () {
var filteredData = $order_logs.jqGrid("getGridParam").lastSelectedData,
allData = $order_logs.jqGrid('getGridParam', 'data');
exportData(filteredData, allData);
}
});
});
function exportData(filteredData, allData) {
if (filteredData.length === 0 || allData.length === 0) {
alert('There is no data to export');
return;
}
// Export only the filtered data
if (filteredData.length > 0) {
return;
}
// Export all the grid data
}
For some reason the value of allData is always an empty array and I am not sure since I am using the same code as everyone is using out there and found in a lot of answer here in SO.
UPDATE:
Currently the grid is holding six columns and a set of 60 records as total paginated by 20 each time however you can change the pagination to be 50 or 100.
Can any tell me why is this?
I'd recommend to use loadonce: true, forceClientSorting: true options in case of small dataset: less at 1000 or 10000 rows. It simplifies the code server side and you can use full functionality of free jqGrid. The problem with access to lastSelectedData and data will be solved.
More then that, you can easy use many advanced features like createColumnIndex: true, generateValue: true of generateDatalist: true options and so on. See demos included in README of version 4.14.1. Good and comfortable filtering of the data is, in my option, the part of displaying the data. Having the data locally allows to find unique values and build <select> in the filter bar or to use <datalist> to have autocomplete functionality.

jqGrid filterToolbar with local data

I have a jQgrid that loads data initially via an ajax call from backend(java struts). Again, this is one time load and once loaded, the jqGrid should operate on the data available locally.
Initially, datatype:json and once loadcomplete, set datatype:local.
Now is there a way to use filterToolbar for local datatype with the following options in free jqgrid;
autocomplete enabled in the toolbar
excel like filtering options
Jqgrid Options:
jQuery("#listTable").jqGrid({
url:'/WebTest/MainAction.do',
datatype: "json",
colNames: ['Label','Value'],
colModel: [
{name:'label',index:'label',width: 40,search:true, stype:'text',sorttype:'int'},
{name:'value',index:'value',width: 56,search:true, stype:'text',sorttype:'text'}
],
autowidth: true,
autoResizing: { compact: true, widthOfVisiblePartOfSortIcon: 13 },
rowNum: 10,
rowList: [5, 10, 20, "10000:All"],
viewrecords: true,
pager: true,
toppager: true,
rownumbers: true,
sortname: "label",
sortorder: "desc",
caption: "Test 235",
height: "200",
search: true,
loadonce: true,
loadComplete: function (data) {
},
gridComplete: function(){
jQuery("#listTable").jqGrid('setGridParam', { datatype: 'local' });
}
}) .jqGrid("navGrid", { view: true, cloneToTop: true})
.jqGrid("filterToolbar")
.jqGrid("gridResize");
All the features are enabled by default if I understand you correctly. The server just have to return all data instead of one page of data to make loadonce: true property work correctly. You need just call filterToolbar after creating the grid. All will work like with local data. You should consider to set sorttype property for correct local sorting and stype and searchoptions for correct filtering of data.
To have "autocomplete" and "excel like filtering options" you need additionally to follow the answer which set autocomplete or stype: "select", searchoptions: { value: ...} properties based on different values of input data. You can do this inside of beforeProcessing callback. The code from the answer use this.jqGrid("getCol", columnName) which get the data from the grid. Instead of that one have access to data returned from the server inside of beforeProcessing callback. So one can scan the data to get the lists with unique values in every column and to set either autocomplete or stype: "select", searchoptions: { value: ...} properties.
UPDATED: I created JSFiddle demo which demonstrates what one can do: http://jsfiddle.net/OlegKi/vgznxru6/1/. It uses the following code (I changed just echo URL to your URL):
$("#grid").jqGrid({
url: "/WebTest/MainAction.do",
datatype: "json",
colNames: ["Label", "Value"],
colModel: [
{name: "label", width: 70, template: "integer" },
{name: "value", width: 200 }
],
loadonce: true,
pager: true,
rowNum: 10,
rowList: [5, 10, "10000:All"],
iconSet: "fontAwesome",
cmTemplate: { autoResizable: true },
shrinkToFit: false,
autoResizing: { compact: true },
beforeProcessing: function (data) {
var labelMap = {}, valueMap = {}, i, item, labels = ":All", values = [],
$self = $(this);
for (i = 0; i < data.length; i++) {
item = data[i];
if (!labelMap[item.label]) {
labelMap[item.label] = true;
labels += ";" + item.label + ":" + item.label;
}
if (!valueMap[item.value]) {
valueMap[item.value] = true;
values.push(item.value);
}
}
$self.jqGrid("setColProp", "label", {
stype: "select",
searchoptions: {
value: labels,
sopt: ["eq"]
}
});
$self.jqGrid("setColProp", "value", {
searchoptions: {
sopt: ["cn"],
dataInit: function (elem) {
$(elem).autocomplete({
source: values,
delay: 0,
minLength: 0,
select: function (event, ui) {
var grid;
$(elem).val(ui.item.value);
if (typeof elem.id === "string" && elem.id.substr(0, 3) === "gs_") {
grid = $self[0];
if ($.isFunction(grid.triggerToolbar)) {
grid.triggerToolbar();
}
} else {
// to refresh the filter
$(elem).trigger("change");
}
}
});
}
}
});
// one should use stringResult:true option additionally because
// datatype: "json" at the moment, but one need use local filtreing later
$self.jqGrid("filterToolbar", {stringResult: true });
}
});

jqgrid, alert with arror after failet add record to database

it's my code:
<script type="text/javascript">
var grid = $("#list");
$(function(){
var grid = $("#list");
grid.jqGrid({
url:'grid.php',
datatype: 'xml',
mtype: 'GET',
colNames:['ID sprzętu','Kod sprzętu', 'Właściciel','Konfiguracja'],
colModel :[
{name:'SprzetID', index:'SprzetID', width:90},
{name:'Kod', index:'Kod', width:120, editable: true},
{name:'Wlasciciel', index:'Wlasciciel', width:200, align:'left', editable: true},
{name:'Konfiguracja', index:'Konfiguracja', width:400, align:'left', editable: true},
],
pager: '#pager',
rowNum:10,
rowList:[10,20,30],
sortname: 'SprzetID',
sortorder: 'asc',
viewrecords: true,
gridview: true,
caption: 'Lista sprzętu'
});
grid.jqGrid('navGrid','#pager',
{add: true, edit: true, del: true, search: true}, //options
{width:400, }, // edit options
{width:400,closeAfterAdd: true, url:'add.php'}, // add options
{reloadAfterSubmit:false}, // del options
{width:600} // search options
);
});
All is great, when adding record to database is correctly, but when for example field "Kod" is duplicate (it's unique field), record can't be add to database... and isn't. I want to display alert with error message, but I can't find in documentation how to do it... I gues,I should use "afterSubmit", but how... I don't know.
Resolved. In add parameters I added code:
afterSubmit: function(response, postdata) {
if(response.responseText != ""){
return [false, response.responseText];
}else{
return [true,"Ok"];
}}

JQgrid get number of rows (loadonce:true)

I have a jqgrid with inline client-side search. When the database returns 0 records I am trying to hide the grid and show a custom message. The problem is that now when I use the filters the same thing happens. I need to get the number of rows from the back-end response and none of the below lines work. When the page loads I get 5 and 5, and when I filter I get 0 and 0. How can this be achieved?
.jqGrid('getGridParam', 'records')
.jqGrid('getGridParam', 'reccount')
var contratsAC=$("#ContratsAC");
contratsAC.jqGrid({
url:'<?php echo base_url().'rest/AC_Rest/get_contrats/'?>',
mtype : "post",
datatype: "json",
colNames:['Nr dossier','Type','Nom','Statut','Date creation','Date derniere maj','Commentaires','Auteur'],
colModel:[
{name:'nr_dossier',index:'nr_dossier',search:false, align:"center"},
{name:'type',index:'type',search:false, align:"center"},
{name:'nomClient',index:'nomClient',search:false, align:"center"},
{name:'statut',index:'statut',search: true, sortable: false, width:180, stype:'select',
searchoptions:{ value:statuts}, editable: false},
{name:'date_cre',index:'date_cre',search:false, align:"center"},
{name:'dern_date_maj',index:'dern_date_maj',search:false, align:"center"},
{name:'commentaires',index:'commentaires',search:false, align:"center"},
{name:'auteur',index:'auteur',search:false, align:"center"}
],
rowNum:10,
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
id: "nr_dossier",
userdata: "userdata"
},
width: 960,
height: "100%",
rowList:[10,20,30],
pager: '#pager1',
sortname: 'nr_dossier',
viewrecords: true,
rownumbers: true,
gridview: true,
loadonce: true,
loadComplete: function(data){
alert(contratsAC.jqGrid('getGridParam', 'records'));
alert(contratsAC.jqGrid('getGridParam', 'reccount'));
if (0==contratsAC.jqGrid('getGridParam', 'records'))
{
contratsAC.jqGrid('GridUnload');
$("#contratsACNoDataMessage").html('<span>Aucun enregistrement a afficher.</span>');
}
else $("#ContratsACContainer").show();
},
pagination:true,
}).navGrid('#pager1',
{add: false,
edit:false,
del:false});
contratsAC.jqGrid('filterToolbar',{searchOnEnter:true,stringResult: true});
You may try getting the length of the data array holded by the grid:
$("#ContratsAC").jqGrid('getGridParam', 'data').length;
The below will give you all the rows - initial data source based
contratsAC.jqGrid('getGridParam', 'records');
To get the number of rows on the current page, lets say after filtering, use
contratsAC.jqGrid('getGridParam', 'reccount');
To get all the records across all pages after filtering, use below
loadComplete: function (gridData) {
var isSearchPerformed = $grid.getGridParam("postData")._search;
if (isSearchPerformed) {
$("#spanFilterTotal").text(gridData.records);
}

jqGrid client side sorting data disappears [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jqgrid client side sorting with server side paging - data disappears
I have a jqGrid and trying to enable client side sorting w/ server side paging. Client side sorting will work if loadonce:true but paging will not work.
If loadonce:false and I try to sort, the data disappears from the grid. Any ideas what I am missing?
jQuery("#grid").jqGrid({
url: getUrl(), // url w/ querystring params
datatype: 'json',
mtype: "GET",
colNames: ['Name', 'Title', 'Office'],
colModel:
[
{ name: 'Employee.EmployeeName', index: 'Employee.EmployeeName', sortable: true, sorttype: 'text' },
{ name: 'Employee.EmployeeTitle', index: 'Employee.EmployeeTitle', sortable: true, sorttype: 'text'},
{ name: 'Employee.EmployeeOffice', index: 'Employee.EmployeeOffice', sortable: true, sorttype: 'text' }
],
width: 600,
height: 'auto',
scrollOffset: 0,
rowNum: 5,
pager: jQuery("#pager"),
rowList: [10, 25, 50],
sortname: 'Employee.EmployeeName',
sortorder: "asc",
loadtext: "Loading....",
emptyrecords: "No records to view",
//loadonce: true, // client side sorting works but paging doesn't work
sortable: true,
viewrecords: true,
jsonReader: {
repeatitems: false
},
loadComplete: function () {
jQuery("#grid").jqGrid('setGridParam', { datatype: 'local' });
jQuery("#grid").trigger("reloadGrid");
},
onPaging: function () {
jQuery("#grid").jqGrid('setGridParam', { datatype: 'json' });
}
});
In my experience, if you do anything server side in JQGrid using JQGrid events, you have to recreate the data on the server and rebind it to JQGrid control. The means you will have to capture the sorting information and account for that as well. The Trirand forums ( http://www.trirand.net/forum/ ) are monitored by the authors of JQGrid. You may get better help there.
Client side sorting will work if loadonce:true but also paging will work fine .
$(document).ready(function() {
$("#user-list").jqGrid({
datatype: "local",
height: "auto",
autowidth: true,
ignoreCase: true,
colNames: ['Emp Id', 'First Name', 'Last Name'],
colModel: [
{name:'emp_id', index:'emp_id', width:55, sorttype:"int"},
{name:'first_name',index:'first_name', width:160, sorttype:"text"},
{name:'last_name',index:'last_name', width:160, sorttype:"text"},
],
pager: '#user-list-pager',
rowNum:10,
rowList:[10,25,50,100],
sortname: 'first_name',
sortorder: 'asc',
viewrecords: true,
caption: 'Users',
data:<%= raw #users_jqgrid_data.to_json %>
});
jQuery("#user-list").jqGrid('navGrid','#user-list-pager',{del:false,add:false,edit:false},{},{},{},{multipleSearch:true});
} );
I just tried a smallcode an paging and sorting works fine here.hope it helps
Thanx

Resources