How to load data (json) in jqgrid via ajax? - ajax

i need to populate jqgrid after ajax's call.
I have a function (in java servelet) that returns this json format:
[{"citta":"XXXX","via":"XXX","telefono":"1111-11111","provincia":"XX","clienteDesc":"Prova","clienteCode":"XXXXX"}]
and i use this code for the jqgrid:
$("#clienti-navgrid").jqGrid( {
//data: c
//datatype: "local"
datatype: "json",
url: '/project/loadnotespese.do',
colNames:['Codice Cliente','Descrizone Cliente','Via','Città','Provincia','Telefono'],
colModel:[
{name:'clienteCode', index:'clienteCode', width:'10', sortable:false},
{name:'clienteDesc', index:'clienteDesc', width:'20', sortable:false},
{name:'via', index:'via', width:'30', sortable:false},
{name:'citta', index:'citta', width:'20', sortable:false},
{name:'provincia', index:'provincia', width:'10', sortable:false},
{name:'telefono', index:'telefono', width:'10', sortable:false}
],
rowNum:500,
autowidth:true,
height:'auto',
recordtext:"Ordini trovati {2}",
emptyrecords:"Nessun risultato",
viewrecords: true,
caption: 'Tabella Clienti',
localReader : {
//
repeatitems: false,
}
});//jqGrid
if i put
var c = [{"citta":"XXXX","via":"XXX","telefono":"1111-11111","provincia":"XX","clienteDesc":"Prova","clienteCode":"XXXXX"}]
and
data: c, datatype: "local",
works, but if i'll get from url: '/project/loadnotespese.do', it dosen't work.
Any help?

If you use datatype: "local" the option localReader will be used. By the way the value repeatitems: false is default value for localReader (see the documentation). So in case of usage datatype: "local" you can event remove the current option localReader: { repeatitems: false } from the list of the options.
On the other side if you use datatype: "json" another option jsonReader will be used. The default value of repeatitems property of jsonReader is repeatitems: false (see the documentation). So you have to add
jsonReader: { repeatitems: false }
in the case to the list of jqGrid options. After that the grid should be successfully filled.
One other important think which is important to know is specifying additional of id property in every item of the row of data. The id value must be unique over the whole page and it will be used as the value of id attributes of the rows (<tr>) elements of the grid body. If some other property of the row items can be used as the unique id you can either include additional setting in jsonReader or add key: true property in the corresponding definition of the column in colModel. For example if clienteCode can be interpreted as the rowid you can use
jsonReader: { repeatitems: false, id: "clienteCode" }
UPDATED: You should use additionally
root: function (obj) { return obj; }
inside of jsonReader (see here). So the final jsonReader should be
jsonReader: {
repeatitems: false,
id: "clienteCode",
root: function (obj) {
return obj;
}
}

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.

jqGrid populate select control on row edit

I want to add about 150 element from a xml file to a select control that is inside a jqGrid cell. I was thinking of doing this in two ways:
1.Using the editoptions value:
{ name: 'language', width: 100, sortable: false, editable: true, edittype: 'select', editoptions: { value: languageElem()} }
using data received from the method:
function languageElem() {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'jqService.asmx/GetLanguages',
data: {},
dataType: "json",
success: function (data) {
alert("success");
}
});}
But I'm having trouble forwarding the data from the ajax part.
2.Simply accessing the select control inside the jqGrid cell and manually adding the options whenever the edit button is pressed.
The problem over here is that I have no idea how to access the control itself.
The code I used over here is:
function startEdit() {
if (selRow > -1) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'jqService.asmx/GetLanguages',
data: {},
dataType: "json",
success: function (data) {
var cell = jQuery("#MainContent_list").getCell(selRow, "language");
cell.options.length = 0;
for (var i=0;i<data.d.length;i++)
{
}
}
});
jQuery("#MainContent_list").jqGrid('restoreRow', selRow);
jQuery("#MainContent_list").jqGrid('editRow', selRow);
}
My questions are:
1.Related to the first idea, what should I do to fix the method so that the control will receive it's needed values?
2.Related to the second idea, how could I access the control inside the row?
Thanks, Catalin
Instead of value property (editoptions: { value: languageElem()}) you should use dataUrl and buildSelect (see the documentation). Because it's difficult to return from ASMX HTML fragment <select><option>...</option></select> you can provide the list serialized as JSON and convert the server response to HTML fragment using buildSelect. In the answer and in this one you will find additional information. If you would search for dataUrl and buildSelect you will find more information and code example which you could use.

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.

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