jqGrid: Load JSON data after local data already in table - javascript

I have a very specific problem: I have a small form with four options. You may fill them out or not, and when you click 'Ok', I load a jqGrid with data depending on those options. But since I do not know what my columns look like, I let my servlet generate the column model and column name; thus I have to make an AJAX request to load the data and then fill it in jqGrid as "local" data. I would like to use pagination though.
Thus my question: How may I load more data into a jqGrid after it is already established through local data?
here's the code:
$.ajax({
type : 'GET',
url : 'data.jsp',
data : reqData,
dataType : 'json',
error: function() {
$("#dialog-message").dialog("open");
$("#ajax-loader").css("display", "none");
},
success : function(result) {
jQuery("#results").jqGrid({
data : result.rows,
datatype : "local",
colNames : result.columnNames,
colModel : result.columnModel,
pager : $('#pager'),
rowNum : 1000,
scroll : true,
viewrecords : true,
sortname : 'TITEL',
width : window.innerWidth - 30,
height : window.innerHeight - 190,
altRows : true,
loadError: function() {
$("#dialog-message").dialog("open");
$("#ajax-loader").css("display", "none");
},
loadComplete: function() {
$("#ajax-loader").css("display", "none");
}
}).jqGrid("navGrid", "#pager", {
edit: false,
add: false,
del: false,
search: true,
refresh: false
}).jqGrid("gridResize");
}
});
/edit: I've tried to do the following, but that still doesn't solve the problem that the grid doesn't know how many total pages there actually are (actually, at that point, I don't even know), and also, after loading, it thinks it only gets local data. Is there maybe an onScroll event or something? I haven't found one.
datatype : !json ? "local" : function(postdata) {
$.ajax({
type: 'GET',
url: 'data.jsp',
data: $.merge(postdata, reqData),
dataType: 'json',
success: function(data, status, jqXHR) {
var mygrid = jQuery("#results")[0];
var myjsongrid = eval("("+jqXHR.responseText+")");
mygrid.addJSONData(myjsongrid);
}
});
},

Can you not do something like this...get the grid, clear the data, define the url to get the data from (it may change depending on what option your user selected) and then change the dataformat to json instead of local.
var grid = $('#TargetGridID');
grid.clearGridData();
grid.setGridParam({ url: '../controller/action?datatype=Option1' });
grid.setGridParam({ datatype: 'json' });
grid.trigger('reloadGrid');
We use this methodology and it works great...use this with stored procedures capable of paging and the grids are blazing fast! I know a 20,000 row grid takes us roughly 700ms with a page count of 500 rows.
If you are using SQL for your data I can upload a sample on how to support paging in a SQL Stored Proc, very useful stuff.

Related

Problems mapping xml / json lsits to select2

I am providing data over REST to a custom HTML form with a SELECT 2 inside it. However I am not able to map the data from REST to the SELECT 2!
javascript for my select2:
$("#space-select").select2({
width : '100%',
ajax : {
delay: 500,
url : url,
type : 'GET',
contentType : 'json',
processResults : function(data) {
return {
results : $.map(data.spaces, function(space) {
return {
id: space,
text: space,
};
})
};
}
}
});
incoming xml:
<configuration>
<spaces>
<space>Space 1</space>
<space>Space 2</space>
<space>Space 3</space>
</spaces>
</configuration>
I dont really understand why the data is not mapped correctly!
SOLUTION:
I found the wrong part in my Code:
i used:
contentType : 'json',
but you have to use:
dataType : 'json',

Set a default value of an extjs 4.2 combobox using AJAX

I have a an extjs 4.2 combobox that I'm using to display some data. Now I'm trying that based on a condition the combo would display a default value. I managed to return the needed data based on that condition, however I'm failing to set the necessary value in the combobox. How am I supposed to set that specific value?
combo:
var locationStore = Ext.create('Ext.data.Store', {
model: 'model_LOCATION',
proxy: {
type: 'ajax',
url: 'Record?DB=GEO&Table=LOCATION',
reader: {
type: 'xml',
record:'record'
}
},
autoLoad:true
});
var C_LOCATION= Ext.create('Ext.form.ComboBox', {
name : 'C_LOCATION',
id : '${DB}.${Table}.C_LOCATION',
store : locationStore,
queryMode : 'local',
displayField : 'display',
valueField : 'value',
});
AJAX call:
var data;
var code = 111;
data = "CODE ='" + code + "'";
var text;
$.ajax({
type: "POST",
url: "Record?DB=GEO&Table=LOCATION",
dataType: 'xml',
data: {
"Where": data
},
success: function(xml) {
text = xml;
Ext.getCmp('${DB}.GEO.LOCATION').setValue(text);
}
});
Give the combo box a reference in the config section (reference: 'comboBox'). Then call comboBox.setValue(defaultValueGoesHere) in your function where you are getting the specific value. You may need to hunt down the comboBox reference depending where you are.
I guess you will have to parse your XML response. Similar as in your code definition for the locationStore, where you specify the record in the xml response.
Why do you make the second ajax call?
Could you not filter the locationStore based on the CODE value, instead?

JqGrid reload is not working without unloading the grid

I am using jqgrid version 4.5.2. I have a role list combobox outside of the grid and on change of the options I need to reload the grid. Below is the defination of my grid.
var finalUrl='';
var queueStatus=jQuery('#queueStatus option:selected').val();
finalUrl= "http://localhost:8080/ui/paw/loadworkflowqueuedata.raws?selRole="+ selectedRole+"&"+queueStatus;
var queueStatus=jQuery('#queueStatus option:selected').val();
finalUrl= "http://localhost:8080/ui/paw/loadworkflowqueuedata.raws?timezone="+&selRole="+ selectedRole+"&"+queueStatus;
jq("#grid").jqGrid('GridUnload');
jq("#grid").jqGrid({
url:finalUrl,
ajaxGridOptions: {cache: false},//added the option to always reload the grid and not to cache the result.
datatype: 'json',
mtype: 'GET',
colNames:[ 'Requestor Name'],
colModel:[
{name:'requestor',index:'requestor',sortable: true, width:100,editable:false, editrules:{required:true}, editoptions:{size:10}}
],
postData: {
},
height: 'auto',
autowidth: true,
rownumbers: true,
pager: '#pager',
viewrecords: true,
sortorder: "asc",
emptyrecords: "Empty records",
loadonce: true,
rowNum:20,
ignoreCase: true,
prmNames: {
nd: null
},
loadComplete: function() {
},
jsonReader : {
root: "rows",
repeatitems: false,
page:"page",
total: "total",
records: "records",
cell: "cell",
id: "id"
}
});
jQuery("#grid").jqGrid('navGrid','#pager',{edit:false,add:false,del:false,search: false, refresh:true})
.navButtonAdd('#pager',{caption:"Export All",buttonicon:"ui-icon-document",onClickButton: function(){window.open(excelUrl,'_self');},position:"last"});
jQuery("#grid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn",ignoreCase: true });
The grid above works fine(refreshes properly on change of rolelist combobox) only if I keep the below statement.
jq("#grid").jqGrid('GridUnload');
If I remove the above statement and reload the page than for the first time grid loads properly but after that If I change the option in my role list combo box it is not able to refresh the grid data neither it is throwing any error.
May I know why I need to unload the grid for refresh? Isn't there a way through which I can refresh the grid with out unloading the grid? Did I miss any options in grid defination that is the reason why grid reload is not working?Please do let me know if need more details for the above question for the solution.
You use loadonce: true options which is very helpful to load all the server data to the client side at once and then working with the data on the client side (paging, filtering and so on) without any communication with the server. To do this jqGrid changes datatype parameter of the grid to "local" after the first loading of data. So you need to reset the value of datatype parameter back to "json" before trigger reloadGrid event.
The corresponding code will be like
// create the initial grid
jQuery("#grid").jqGrid({
...
url: finalUrl,
datatype: 'json',
loadonce: true,
...
});
jQuery('#queueStatus').change(function () {
jQuery("#grid").jqGrid("setGridParam", {
datatype: "json",
url: "basePartOfUrl?" + jQuery.param({
timezone: "blabla",
selRole: jQuery('#queueStatus').val();
})
}).trigger("reloadGrid");
});
I use above jQuery.param instead of direct construction of parameters in the string to make the code more correct. Alternatively one should use encodeURIComponent to construct the parameter values appended to URL. It's clear that one can use queueStatus directly if it has no space, no special characters and so on, but the usage of encodeURIComponent or jQuery.param is still recommended and make the code working independent from the value of the string parameter.

JqGrid don'i reload after click on the button

I work with jqGrid on my project and I have a problem that can not seem to solve even after reading the forums on the same subject.
I would reload the grid when a user clicks a button after selecting a date. I want the data recharge correspodent to choose the date.
I use the following code:
var loadfacture = false;
$('#btn-facture').click(function(){
if(!loadfacture){
$("#factures").jqGrid({
url:'loadfactureencours.json',
datatype: "json",
autowidth: true,
height:250,
colNames:['#','Numero','Date', 'Client','Serveur','Prix Total','Avance','Regler','Notes'],
colModel:[
{name:'idfac',index:'idfac', width:45,align:"center"},
{name:'numfac',index:'numfac', width:80,align:"center"},
{name:'datefac',index:'datefac', width:150,align:"center"},
{name:'client',index:'client', width:145,align:"center"},
{name:'utilisateur',index:'utilisateur', width:125,align:"center"},
{name:'montant',index:'montant', width:70,align:"center"},
{name:'avance',index:'avance', width:60,align:"center"},
{name:'regler',index:'regler', width:50,align:"center"},
{name:'description',index:'description', width:150, sortable:false}
],
rowNum:10,
rowTotal: 2000,
rowList : [10,20,30,40,50,60],
loadonce:true,
mtype: "GET",
postData: {
day: function () {
return $('#daySelect').val();
}
},
rownumbers: false,
rownumWidth: 40,
gridview: true,
pager: '#paging',
sortname: 'idfac',
viewrecords: true,
sortorder: "desc",
caption: "",
ondblClickRow: function(rowid,iRow,iCol,e){
var rowData = jQuery(this).getRowData(rowid);
console.log(rowData);
window.location = "ecrancommandebar.html?num="+rowData.numfac;
}
});
$("#factures").jqGrid('navGrid','#paging',{del:false,add:false,edit:false});
loadfacture = true;
}else{
var grid = $("#factures");
grid.trigger("reloadGrid",[{current:true}]);
}
});
I built this piece of code by reading the forum on the same subject but the grid load the first time then when I click on the button after changing the date nothing happens.
What is wrong with you? Thank you for your feedback.
You use loadonce:true option which changes datatype from initial "json" to "local" after the first loading of the data from the server. It allows to support local sorting, paging and filtering of data. So you should understand that grid.trigger("reloadGrid",[{current:true}]); will just reload the data from previously saved previous response. So no reloading from the server will take place till you reset the value of datatype parameter to "json". In other words you should rewrite else part to about the following
...
} else {
$("#factures").jqGrid("setGridParam", {datatype: "json"})
.trigger("reloadGrid", [{current: true, page: 1}]);
}
You can try with this:
}else{
var grid = $("#factures");
$.ajax({
url: "loadfactureencours.json",
dataType: "json",
success: function(data){
grid.trigger("reloadGrid",[{current:true}]);
},
error: function(){}
});
}

How to disable autoload in jqGrid?

How to disable autoload in jqGrid and load data manually when I need it?
Thanks.
If you set datatype to 'local' the data from the server will be not loaded. To force the loading of data you can change datatype to 'json' or 'xml' with respect of setGridParam method (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options and http://www.trirand.com/jqgridwiki/doku.php?id=wiki:methods#grid_related_methods) and then call trigger("reloadGrid") method.
See jqGrid is not loading data which has also the information what you asked.
Just don't set the default URL in the table. And install it just when you need to load data (for example by pressing a button) and then .trigger("reloadGrid").
Example for you:
jQuery("#grid").jqGrid(
{
//Simply comment out the URL
//url :"salepointsprovider.php",
datatype:"json",
colModel :[
{name:'SalePointId', index:'SalePointId'},
{name:'Name', index:'Name'}
]
}
$('#ShowRecordsButton').click(function () {
jQuery("#grid").jqGrid('setGridParam',
{url:"salepointprovider.php?SalePointId=" + argSalePointId, page:1});
jQuery("#grid").trigger('reloadGrid');
}
My grid without url send requests to server:
.../?_search=false&nd=1370817124473&rows=20&page=1&sidx=&sord=asc
Set datatype: "local" solve problem.
Reload grid by
`function reloadGrid(gridId, gridData){
$(gridId).jqGrid('clearGridData'); // need for nonempty grig (see http://www.trirand.com/blog/?page_id=393/help/triggerreloadgrid-not-work/)
$(gridId).jqGrid('setGridParam', {data: gridData}).trigger('reloadGrid');
}
`
No need to change datatype (at least for my json case it is recognized)
In treegrid you couldn't use datatype = 'local'. So instead 'local', I set datatype = 'jsonstring', define empty fake data and jsonReader. jsonReader should be defined correctly according to your retrieved data. Thanks for Oleg's answer. And, when I need to load data, I simply change datatype to 'json'.
var fakeData ={
rows: []
};
...
datatype: 'jsonstring',
datastr: fakeData,
...
jsonReader: {
repeatitems: false,
root: function (obj) { return obj.rows; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
}

Categories