Loading json data into jqgrid using setGridParam - jqgrid

I'm having some issues setting the url of the jqgrid using setGridParam.
I receive the message: "f is undefined".
My setup:
$("#prices").jqGrid({
colModel: [
...
],
pager: jQuery('#pricePager'),
ajaxGridOptions: { contentType: "application/json" },
mtype: 'POST',
loadonce: true,
rowTotal: 100,
rowNum: -1,
viewrecords: true,
caption: "Prices",
height: 300,
pgbuttons: false,
multiselect: true,
afterInsertRow: function (rowid, rowdata, rowelem) {
// ...
},
beforeSelectRow: function (rowid, e) {
// ...
},
onSelectRow: function (rowid, status) {
// ...
}
});
Getting the data:
$("#prices").setGridParam({ datatype: 'json', page: 1, url: '#Url.Action("GridDataPrices")', postData: JSON.stringify(selections) });
$("#prices").trigger('reloadGrid');
The Response is non encoded json:
{"total":1,"page":1,"records":100,"rows":[{"id":160602948,"StartDate":"\/Date(1311717600000)\/","Duration":7,"Price":1076.0000,"Code":"code"},{"id":160602950,...}]}
However, I get following message, using firebug:
"f is undefined"
I got this working first using addJSONData, but had to replace it because I want to preserve the local sorting.
Thanks in advance.

After you uploaded the code all will be clear. Your main errors are the follwings:
you should include datatype: 'local' in the jqGrid. Default value is 'xml'.
the JSON data have named properties so you have to use jsonReader: { repeatitems: false } (see the documentation for details)
you use "ArivalCodeWay" in colModel and "ArrivalCodeWay" in the JSON data. So you should fix the name of the corresponding jqGrid column
to decode the date from the "\/Date(1312840800000)\/" format you should include formatter:'date' in the corresponding column.
In the same way I find good to include formatter:'int', sorttype:'int' in the 'Duration' column and sorttype:'number', formatter:'number', formatoptions: { decimalPlaces:4, thousandsSeparator: "," } in the 'Price' column.
if you use JSON.stringify you should include json2.js to be sure that your code will work in all web browsers.
The modified demo (including some other minor changed) you can find here. If you click on "Click me" button the grid contain will be loaded.

Related

How to access id of onSelectRow in delOptions action method in jqGrid

//Hidden Input element
//my grid details:
$("#jqGrid").jqGrid({
url: '#Url.Action("EditedEventData", "Calendar" ,new{ })' + '?CountryId=' + #countryid + '&CityId=' + #cityid ,
async: true,
datatype: "json",
colModel: [
//label: "Edit Actions",
name: "",
width: 100,
formatter: "actions",
formatoptions: {
keys: true,
edit: true,
add: true,
del: true,
editOptions: {},
addOptions: {},
delOptions: {
url:'#Url.Action("RemoveEvent", "Calendar")'+ '?HolidayId='+document.getElementById('hdnEventId').value ,
//mtype: 'POST',
}// **here it is showing hdnEventId value empty**
}
}
],
onSelectRow : function(id){
console.log('inside onSelectRow');
alert(id);
document.getElementById('hdnEventId').value=id;
alert(document.getElementById('hdnEventId').value);
},
sortname: 'EventDate',
loadonce: true,
width: 750,
height: 200,
rowNum: 150,
pager: "#jqGridPager"
});
I am unable to access id of onSelectRow in delOptions action method.
So thought of taking a hidden html element and store the value but it is showing empty.
Thanks in advance
When a delete is performed the id is automatically send to the server. The parameter which is obtained via post is named id.
If you additionally want to fill a id on deleting a rows you can use some events to fill the field you want. These are described here. In the same documentation see the chapter What is posted to the server .
To fill the id in another field when a row is deleted I think the good choice is to use either serializeDelData or afterSubmit events - see the events on the same link.
When use these events the parameter postdata contain the id. By example in serializeDelData (set this in delOptions) this can look like
serializeDelData : function( postdata ) {
var id = postdata.id;
document.getElementById('hdnEventId').value=id;
return postdata;
}
Remember both events should return some params

jqGrid: function $("#gridView").jqGrid("getGridParam", "data") return null?

I had a problem with jqGrid
When i use:
$("#gridView").jqGrid({
url:"grid.php",
colModel:[
{ name: 'id', index:'id'},
],
datatype: "json",
mtype:"post",
height:350,
rownumbers:true,
treeGrid: true,
treeGridModel : 'adjacency',
ExpandColumn : 'id',
ExpandColClick: true
....
$("#gridView").jqGrid("getGridParam", "data") return array
$("#gridView").jqGrid({
url:"grid.php",
colModel:[
{ name: 'id', index:'id'},
],
datatype: "json",
mtype:"post",
pager:"#pager",
rowNum:50,
rowList:[10,50,100,500,1000],
viewrecords:true,
height:350,
rownumbers:true,
....
$("#gridView").jqGrid("getGridParam", "data") return null ??
I've read article here JQGrid getGridParam not returning ID of data item
But I cannot set loadonce:true because of my dynamic data for each click
You don't need to use loadonce: true in case of treeGrid: true. jqGrid fills internal parameters data and _index for treegrid automatically (see the part of the code).
I suppose that you get null as the value of data parameter because you try to access data before the data will be loaded from the server. Try to use $(this).jqGrid("getGridParam", "data") inside of loadComplete callback. The callback will be called after filling of data.

SetLabel method of jqGrid along with setGroupHeaders

I am trying to use setlabel method of jqGrid along with setGroupHeaders. It does not work. But when I remove this setGroupHeaders, setLabel method works and I am able to change my column headers dynamically. Is there anyway to use both of the methods together?
Adding the code fragment
$("#aGrid").jqGrid({
shrinkToFit: false,
autowidth: true,
height: 305,
colNames: ['Parameter','T0','T1','T2','T3'],
colModel: [
{name:"paramName",index:"paramName",width:115,sortable:false,frozen:true},
{name:"t0",index:"t0",cellattr:myFormatter,hidden:false},
{name:"t1",index:"t1",cellattr:myFormatter,hidden:false},
{name:"t2",index:"t2",cellattr:myFormatter,hidden:false},
{name:"t3",index:"t3",cellattr:myFormatter,hidden:false}
],
viewrecords: true,
gridview: true,
sortable: false,
caption: "A Grid"
});
$("#aGrid").jqGrid('setGroupHeaders', {
useColSpanStyle: true,
groupHeaders: [
{startColumnName:'t0',
numberOfColumns:8,
titleText:'10.152.141.142'}]
});
$.ajax({
type : "get",
url : url,
dataType: "json",
contentType: "application/json",
success : function(responseText){
for(var i=0;i<=responseText.length;i++)
{
if(i === 0){
var newColHeaders = responseText[i];
$("#aGrid").jqGrid('setLabel', "t0",newColHeaders['t0']);
$("#aGrid").jqGrid('setLabel', "t1",newColHeaders['t1']);
$("#aGrid").jqGrid('setLabel', "t2",newColHeaders['t2']);
$("#aGrid").jqGrid('setLabel', 't3',newColHeaders['t3']);
}else{
$("#aGrid").jqGrid('addRowData',i+1,responseText[i]);
}
}
},
error: function(xhRequest, ErrorText, thrownError){
}
});
If I use the same code after removing setGroupHeaders call in above code, column headers change works as expected.
This issue is because of your group header.
When you want to change the header, first destroy the group header and then call the setLabel and again reconstruct the group Header.
$("#aGrid").jqGrid('destroyGroupHeader');
//Now change the Label of header
$("#aGrid").jqGrid('setLabel', "to","ABC"); //colModel name value
constructGroupHeader();
Construct group Header should be like this
function constructGroupHeader()
{
jQuery("#aGrid").jqGrid('setGroupHeaders', {
useColSpanStyle: true,
groupHeaders: [
{startColumnName:'t0',
numberOfColumns:8,
titleText:'10.152.141.142'}]
});
}
Hope this helps.

passing csrf token through jqgrid on cell edit

I'm using Codeigniter and jqgrid to build an application. I've recently enabled Codeigniter's builtin CSRF protection for security reasons, and it broke some stuff with jqgrid. I've been able to pass the csrf token when jqgrid is instantiated so all my data loads (by adding the csrf token to the postData), but now anytime I edit a cell I get a 500 error because the csrf token isn't being passed. I can verify this by looking at the post data each time I edit a cell. I read several places that editData is what I want, but adding the token in there doesn't seem to pass it in the edit ajax request. Any ideas?
$("#cust_grid").jqGrid({
url:'/ajax/grid',
datatype: 'xml',
mtype: 'POST',
postData: {<?php echo $this->security->get_csrf_token_name().":'".$this->security->get_csrf_hash()."'"; ?>},
editData: {<?php echo $this->security->get_csrf_token_name().":'".$this->security->get_csrf_hash()."'"; ?>},
colNames:['Name1', 'Name2'],
colModel :[
{name:'name1', index:'name1', width:55, search: true},
{name:'name2', index:'name2', width:110, search: true},
],
pager: '#pager',
rowNum:25,
rowList:[10,25,50,100],
sortname: 'name1',
sortorder: 'asc',
viewrecords: true,
gridview: true,
caption: 'Customers',
height: 600,
width: 1200,
shrinkToFit: false,
altRows: true,
cellEdit: true,
cellsubmit: "remote",
cellurl: "/ajax/editCell",
},
{}
);
It seems that you can solve the problem mostly in the same way like I described here. The main difference is that you use cell editing instead of form editing. So you should use ajaxCellOptions instead of ajaxEditOptions:
ajaxCellOptions: {
loadBeforeSend: function(jqXHR) {
// you should modify the next line to get the CSRF tocken
// in any way (for example $('meta[name=csrf]').attr('content')
// if you have <meta name="csrf" content="abcdefjklmnopqrstuvwxyz="/>)
var csrf_token = '<%= token_value %>'; // any way to get
jqXHR.setRequestHeader('X-CSRF-Token', csrf_token);
}
}
I ended up finding another solution to the problem. I was investigating the cell editing link posted in the another answer and I saw the beforeSubmitCell option. Turns out if you return json data from that function it will be appended to the post data each time a cell is edited. So all I needed to do was add as an option:
beforeSubmitCell: function (rowid,celname,value,iRow,iCol) {
return {<?php echo $this->security->get_csrf_token_name().":'".$this->security->get_csrf_hash()."'";?>}
},
No answer working out after I tried. Then i found the solution for passing CSRF Token from Jqgrid inline editing to Django by using this :
onSelectRow: function(id){
if(id && id!==lastSel){
$(selector).restoreRow(lastSel);
lastSel=id;
}
var editparameters = {
extraparam: {csrfmiddlewaretoken: $('.token-data').data('token')},
keys: true,
};
$(selector).jqGrid('editRow', id, editparameters);
}
Example usage :
http://yodi.polatic.me/jqgrid-inline-editing-integration-with-django-send-csrf-token/

jqGrid edit record form empty

I've implemented a jqGrid, but when I try to use the built-in form edit feature, an empty form pops up.
For every column i have set editable:true except for the table's primary key, an auto-incremented id. What am I doing wrong? Do I need to have a valid editurl, rather than clientArray? Below is the jqGrid implementation:
$.ajax({
type: "GET",
url: colUrl,
datatype: "json",
success: function(result){
result = jQuery.parseJSON( result )
var colN = result.colNames;
var colM = result.colModelList;
$("#jqTable").jqGrid({
url:dataUrl,
datatype: 'xml',
mtype: 'GET',
colNames:colN,
colModel:colM,
shrinkToFit: false,
caption: db + "." + table,
pager: '#jqPager',
rowNum:10,
rowList:[10,20,30],
sortname: 'dbid',
editurl: 'clientArray',
sortorder: 'asc',
viewrecords: true,
width: 1000,
height: 400
});
$("#jqTable").jqGrid('navGrid', '#jqPager',
{edit:true, add:false, del:false, search:true, view:false}, //options
{}, // edit options
{}, // add options
{}, // del options
{multipleSearch:true,
sopt : ['eq',//equals
'ne',//not equals
'lt',//less than
'le',//less than or equal
'gt',//greater than
'ge',//greater than or equal
'bw',//begins with
'bn',//does not begin with
'in',//in
'ni',//not in
'ew',//ends with
'en',//does not end with
'cn',//contains
'nc']//does not contain
}, // search options
{} //view options
);
},
error: function(x,e){
alert(x.readyState + " " + x.status + " " + e.msg);
}
});
and here is sample colModel and ColName string:
"colModelList": [{"name":"dbid","index":"dbid","editable":"false"},{"name":"description","index":"description","editable":"true"},{"name":"file_name","index":"file_name","editable":"true"}],"colNames": ["dbid","description","file_name"]
I suppose that the reason is because you use "editable": "true" or "editable": "false" instead of "editable": true or "editable": false.
Moreover you try to use form editing for the local data editing. The current jqGrid implementation support local data editing only for cell editing and inline editing. If you do need to use form editing to edit local data you can find my demo in the answer. The code will be longer, but it is do possible to implement this.

Resources