passing csrf token through jqgrid on cell edit - ajax

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/

Related

jqGrid : searchrules in single Field searching

I'm trying to validate the search field for integer data alone but unfortunately am unable to do so. I have tried all possible solutions like searchrules:{required:true,integer=true} etc..
But none of them proves fruitful.
I basically launch the search dialog with the field and without inputting any data, am hitting on the 'Find' button. As per the above options, i believe a validation message should be shown to the user asking him to enter a value in the field before hitting find.
[UPDATED] - Code Snippet
var grid = $("#list");
grid.jqGrid({
url:'/index.jsp',
datatype: 'json',
mtype: 'POST',
colNames:['Name','Age', 'Address'],
colModel :[
{name:'name', index:'name', width:55,search:true },
{name:'age', index:'age',
width:90,editable:true,search:true, stype:'text',
searchrules:{required:true,integer:true}},
{name:'address', index:'address', width:80,
align:'right', editable: true,search:false }
],
pager: '#pager',
jsonReader : {
root:"address",
page: "page",
total: "total",
records: "records",
repeatitems: false
},
rowNum:10,
rowList:[10,20,30],
sortname: 'name',
sortorder: 'desc',
viewrecords: true,
gridview: true,
autowidth: true,
toppager: true,
loadtext: "Loading records.....",
caption: 'Test Grid',
gridComplete: function(){
}
});
**grid**.jqGrid('navGrid','#pager',
{view:true,edit:true,add:true,del:true,refresh:true,
refreshtext:'Refresh',addtext:'Add',
edittext:'Edit',cloneToTop:true,
edittitle: "Edit selected row"},
{},{},{},
{caption: "Search The Grid",Find: "Find Value",Reset: "Reset"},
{});
[Updated] : Am not able to make the searchrules properly work for the single/advanced searching modes.
[Updated] : Even the 'Validation in Search' in
jqGrid Demo is not working for searchrules.
The reason of described problem is a bug in jqGrid. The line
ret = $.jgrid.checkValues(val, -1, null, colModelItem.searchrules, colModelItem.label);
initialize the third parameter of $.jgrid.checkValues to null, but the last version of checkValues implementation started (see the line) with
var cm = g.p.colModel;
but g is initialized to null. The last modification which generates the error was based on my suggestion, but I don't wrote the part of the code.
One can solve the problem in different way. I would suggest to modify the line where $.jgrid.checkValues will be called with null parameter to the following
ret = $.jgrid.checkValues(val, -1, {p: {colModel: p.columns}}, colModelItem.searchrules, colModelItem.label);
Additionally, to be sure, I would suggest to modify one more line
if(!nm) { nm = g.p.colNames[valref]; }
to
if(!nm) { nm = g.p.colNames != null ? g.p.colNames[valref] : cm.label; }
The fixed version of jquery.jqGrid.src.js one can get here. I will post my bug report with the same suggestions later ti trirand.

Codeigniter with jqGrid: use csrf_token

If in config file I set csrf_token to false and everything works. However when csrf_token is true, my grid can only get data from database but not update or anything else.
I'm looking through the posts on this site about Сodeigniter+jqGrid but still haven't understand what should I do.
I can get the value of csrf_token but where it should be included?
var lastsel;
var addl_params =
{
ci_csrf: $.cookie('ci_csrf_token')
};
$("#grid").jqGrid({
url:'url to script',
datatype: "json",
mtype: 'GET',
colNames:['id', 'Nickname', 'Breed'],
colModel:[
{name:'id',index:'id', width:55, sortable:false, editable:false,
editoptions:{readonly:true,size:10}},
{name:'nickname',index:'nickname', width:100,editable:true,
edittype:"text"},
{name:'breed',index:'breed', width:100,editable:true, edittype:"text"},
],
jsonReader : {
root:"rows",
page: "page",
total: "totalpages",
records: "records"
},
rowNum:10,
rowList:[10,20,30],
pager: jQuery('#gridpager'),
sortname: 'nickname',
viewrecords: true,
sortorder: "asc",
caption:"Cats",
onSelectRow: function(id){
if(id && id!==lastsel){
jQuery('#grid').jqGrid('restoreRow',lastsel);
jQuery('#grid').jqGrid('editRow',id,true,null, null);
lastsel=id;
}
},
editurl:"edit-url"
}).navGrid('#gridpager');
First it's necessary to understand CSRF:
http://www.beheist.com/index.php/en/blog/csrf-protection-in-codeigniter-2-0-a-closer-look
From that post:
"The Security class generates a unique value for the CSRF token with
each HTTP request. When the object is created, the name and value of
the token are set."
What is possibly happening (I'm not familiar with jqGrid) is each form is possibly getting it's own CSRF token. Or, it's possible that there is only one token for all the forms. Either way, CodeIgniter expects one token per HTTP request and response. Basically, you need to close the loop on the first request to create the page, and the POST of the data.
Therefore, you may need to dig into the jqGrid code and the CI view to make sure that your output generates the CSRF token as desired.
Update: One of the comments on the blog above had a link to Ajax CSRF problems: http://aymsystems.com/ajax-csrf-protection-codeigniter-20

customize: POST output in jqGrid without changing source file?

I'm trying to turn jqGrid within MODx, as do other data exchange using "$. ajax", move the call from a URL to a resource protected by a password and from there call a snippet of code in PHP, so the security framework, the ajax call is guaranteed
This is one example of a chunk $.ajax:
$.ajax ({
url :'[[~94]]',
type: 'post',
async: false,
success: function(rsp) {
$.Cookie("xxxxxx-tipodirlist", rsp);
}
});
*[[~94]] is a protected resource is within a snippet call [[!SnpBridgedata_blabla]]
the system works perfectly well throughout the web application, receiving and sending data safely and securely.
Now a customer asked me for a completed application wanted web results in a good grid and after seeing a bit of code I decided to use jqGrid for my project.
integration was quick and I am very happy to have changed "DataTable" with "jqGrid," but when I finished the test, change the absolute path to xxxxxx.php with the call to snippet
this is the code for jqGrid:
chargeSedi function (idx)
{
// Test with file. Php !work fine!
// Var esURL = 'http://xxxxx.com/xxxxxxx.php?IDX =' + idx;
// Test with MODx resource !not work!
esURL var = '[[~ 97]] & IDX =' + idx;
csURL var = '[[~ 96]] & IDX =' + idx;
tipodirlist = $ var. cookie ("xxxxxxxx-tipodirlist");
tiposedelist = $ var. cookie ("xxxxxxx-tiposedelist");
$("#sediTable").ready(function() {
$("#sediTable").jqGrid({
url:csURL,
datatype: "json",
height: 250,
autowidth:true,
colNames:[ 'ID','CODICE', 'NOME','TDIR', 'DIR','COMUNE', 'PROVINCIA','CAP', 'TSEDE','NOTA'],
colModel:[
{name:'ID',index:'ID', width:25, editable: false},
{name:'CODICE',index:'CODICE', width:60, editable: true},
{name:'NOME',index:'NOME', width:60, editable: true},
{name:'TDIR',index:'TDIR', width:60, editable: true,edittype:"select",editoptions:{value:tipodirlist}},
{name:'DIR',index:'DIR', width:200, sortable:false,editable: true},
{name:'COMUNE',index:'COMUNE', width:170, sortable:false,editable: true},
{name:'PROVINCIA',index:'PROVINCIA', width:170, sortable:false,editable: true},
{name:'CAP',index:'CAP', width:40, sortable:false,editable: true},
{name:'TSEDE',index:'TSEDE', width:90, editable: true,edittype:"select",editoptions:{value:tiposedelist}},
{name:'NOTA',index:'NOTA', width:170, sortable:false,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"10"}} ],
sortname: 'ID',
viewrecords: true,
sortorder: "desc",
loadonce: true,
editurl: esURL ,
caption: "Sedi" });
});
]
and for my surprise the MODx deny Access to jqGrid ajax calls, as if you were out of session, but after hours testing and watching the traffic with wireshark I realized that jqGrid sends a POST variable called "id" and call MODx a GET variable "id". this in other environments is possible without problem, but it is not possible MODx and there's the problem.
my question is how I can change the name of the POST variable "id" jqGrid, without changing the source of jqGrid?
at the same time wanted to ask, you can customize the import of a select the value and not the index
example of trame POST:
{Name: 'TDIR', index: 'TDIR', width: 60, editable: true, EditType: "select" editoptions: {value: tipodirlist}}
tipodirlist = 1:via;2:piazza;3:ect
TDIR=2
CODICE=1&NOME=principale&TDIR=2&DIR=Roma&COMUNE=Torino&PROVINCIA=Torino&CAP=10000&TSEDE=2&NOTA=NO=edit&id=0
for this:
TDIR=piazza
CODICE=1&NOME=principale&TDIR=piazza&DIR=Roma&COMUNE=Torino&PROVINCIA=Torino&CAP=10000&TSEDE=2&NOTA=NO=edit&id=0
without having to filter the results on the server.
I hope I've explained well and clear. as I asked myself, the team "StackOverflow" before asking this question
Thank you so much
Regards
niro.
PS.I hope that GOD "Oleg" help me:)
I don't know and don't use MODx. Nevertheless I hope that your problem is: how to rename the name of the id parameter to have no conflict with the id parameter used by MODx.
If I understand your question correct you should just add additional prmNames parameter which set the new name of id parameter used in editing operations:
prmNames: {id: 'myId'}
The example will rename the default id parameter name ({id: "id"}) to myId which you should you in your server part.

Loading json data into jqgrid using setGridParam

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.

Fire an event after a local delete jqgrid

So what I am trying to do is fire an event AFTER a local delete has been done on the jqgrid. The reason for this is because I am dealing with a global save on the website so I am not posting directly to the server. I am storing the data in JSON form within a hidden element on the page so when the user finally saves the element value is grabbed and sent to the server along with all the other data.
The issue I am having is that when I delete a row from the jqgrid I am not able to update the hidden element with the change, so if the user saves after that it is like the remove never happened.
$("#translationMappingGrid").jqGrid({
data: mydata,
datatype: "local",
mtype: 'GET',
colNames:['From','To', 'Type'],
colModel :[
{name:'from',index:'from', width:180, align:"left",sorttype:"float", editable: true, editrules:{custom:true, custom_func:validateIPGridInput}},
{name:'to',index:'to', width:180, align:"left",sorttype:"float", editable: true, editrules:{custom:true, custom_func:validateIPGridInput}},
{name:'type',index:'type', width:200,align:"left",sorttype:"float", editable: true,
edittype:"select", formatter:'select', editoptions:{
value:"0:Never Translate;1:Always Translate;2:Only If Source;3:Only If Destination"}
},
],
pager: '#pager',
rowNum:10,
rowList:[10,20,30],
sortname: 'invid',
sortorder: 'desc',
viewrecords: true,
gridview: true,
caption: 'Mapping',
editurl: 'probe.sysinfo.ajax',
url:'clientArray',
onSelectRow: function(id){
jQuery('#translationMappingGrid').jqGrid('restoreRow',lastsel2);
//below are the parameters for edit row, the function is called after a successful edit has been done
//jQuery("#grid_id").jqGrid('editRow',rowid, keys, oneditfunc, succesfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc);
jQuery('#translationMappingGrid').jqGrid('editRow',id,true,"","","","",function () {
setTranslationMappingJSON(getGridDataJSONString(this));
window.parent.document.getElementById('notificationDiv').style.display= "";
});
lastsel2=id;
},
afterInsertRow: function(rowid, rowdata, rowelem ){
//alert("after insert row");
setTranslationMappingJSON(getGridDataJSONString(this));
window.parent.document.getElementById('notificationDiv').style.display= "";
}
});
//adds buttons to jqgrid nav bar
jQuery("#translationMappingGrid").navGrid('#pager',{
edit:false,add:true,del:true,search:false,refresh:true
}, {
closeAfterAdd:true,
closeAfterEdit: true
},
{
closeAfterAdd:true,
closeAfterEdit: true,
afterSubmit: function(response, postdata) {
alert("after complete row");
setTranslationMappingJSON(getGridDataJSONString(this));
window.parent.document.getElementById('notificationDiv').style.display= "";
return [true,""];
}
});
As indicated in the code above I am successfully updating the hidden element with the changes on both add and edit (inline) via afterrestorefunc, but this is not working for delete.
I have tried using afterSubmit in the code above, but this is not working either. I have been working on this for a few days now and have come to the conclusion that I might have to write my own custom code for the delete button entirely, but I am hoping this is not the case.
The OP wrote in an edit:
So it appears as though I was staring at the issue for too long and was missing the obvious....lucky me. I found out two things:
Using afterSubmit was the wrong thing to use, instead I should be using afterComplete.
I had tried using afterComplete before trying afterSubmit and the reason it was not working it because I am putting them both within the "add" parameters and NOT the delete. Once again, I feel pretty awesome for that one :)
Well now that I have figured that out here is the code snippet that saved my life:
jQuery("#translationMappingGrid").navGrid('#pager',{
edit:false,add:true,del:true,search:false,refresh:true
}, {
closeAfterAdd:true,
closeAfterEdit: true
},
{
closeAfterAdd:true,
closeAfterEdit: true
},{
afterComplete:
function () {
//saves the changed JSON string to the hidden element
setTranslationMappingJSON(getGridDataJSONString(jQuery('#translationMappingGrid')));
window.parent.document.getElementById('notificationDiv').style.display= "";
}
});
This is tested and the function is called after the delete has been performed and saves the local changes to my hidden element.
For anyone who is curious about what the format is:
/* The following is the setup
navGrid(<name>, {<buttons, true/false},
{
<edit parameters>
},
{
<add parameters>
},
{
<delete parameters>
}
*/
Thanks for everyone who might have started working on this, and definitely thanks to the developers of jqgrid. Best javascript grid I have ever worked with!

Resources