How to disable autoload in jqGrid? - javascript

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; }
}

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?

jquery Datatables filter rows

Hi I have a DataTables DataTable object which requests json data via an ajax call. Each object inside the json data has a property called state that can be one of a number of values. Ultimately, I'd like to create several (Data)tables, one for each state without having each table request the same data via ajax again and again. For now, I haven't managed to make a single table filter out the rows with incorrect state yet and I'd like to solve this problem first.
The DataTable object defined as follows:
$(document).ready(function () {
var table = $('#example').DataTable({
data: example,
ajax: {
url: "{{ callback_url }}",
dataType: 'json',
dataSrc: '',
},
createdRow: function (row, data, index) {
},
columns: [{
data: "Type"
}, {
data: "State",
}
}]
});
});
I want to filter the data that comes from the ajax call based on a parameter (e.g. "if (row.State == 'new') {...};"). How can I do that? Does datatables have a function that can be passed to filter each row?
I really need several tables which show data from the same ajax callback but in different states (e.g. a "New" table, an "Old" table etc.). How can I do this without requesting the same json data again and again for each table rendered? Ideally I can store the ajax in a variable but with the async process I'm not sure how this will work out.
You can use one ajax and store the data, and than create each datatable.
Example:
$(document).ready(function () {
var data = null;
$.ajax(URL, {
dataType: 'json',
success: function(ajaxData){
data = ajaxData;
newData = data.filter(function(item){ return item.State == "New"});
oldData = data.filter(function(item){ return item.State == "Old"});
var newTable = $('#newTable').DataTable({
data: newData,
});
var oldTable = $('#oldTable').DataTable({
data: newData,
});
}
});
}

Persist additional dataSource.read parameters on paganation in Kendo data grid

I have a Kendo Grid that loads data via ajax with a call to server-side ASP.NET read method:
public virtual JsonResult Read(DataSourceRequest request, string anotherParam)
In my client-side JS, I trigger a read when a button is clicked:
grid.dataSource.read( { anotherParam: 'foo' });
grid.refresh();
This works as expected, only I lose the additional param when I move through the pages of results in the grid, or use the refresh icon on the grid to reload the data.
How do I persist the additional parameter data in the grid?
I have tried setting
grid.dataSource.data
directly, but without much luck. I either get an error if I pass an object, or no effect if I pass the name of a JS function that returns data.
if you want to pass additional parameters to Read ajax datasource method (server side), you may use
.DataSource(dataSource => dataSource
...
.Read(read => read.Action("Read", controllerName, new { anotherParam= "foo"}))
...
)
if you want to pass additional parameters through client scripting you may use datasource.transport.parameterMap, something as below
parameterMap: function(data, type) {
if (type == "read") {
return { request:kendo.stringify(data), anotherParam:"foo" }
}
Use the datasource.transport.parameterMap
parameterMap: function(data, type) {
if (type == "read") {
return kendo.stringify(data, anotherParam);
}
I'm not sure where your other param is coming from, but this is generally how I send extra parameters to the server.
http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configuration-transport.parameterMap
if use datasource object :
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '/Api/GetData',
contentType: "application/json; charset=utf-8", // optional
dataType: "json",
data: function () {
return {
additionalParam: value
};
}
},
//parameterMap: function (data, type) {
// and so use this property to send additional param
// return $.extend({ "additionalParam": value }, data);
//}
},
schema: {
type: "json",
data: function (data) {
return data.result;
},
},
pageSize: 5,
serverPaging: true,
serverSorting: true
});
and set options in grid:
$("#grid").kendoGrid({
autoBind: false,
dataSource: dataSource,
selectable: "multiple cell",
allowCopy: true,
columns: [
{ field: "productName" },
{ field: "category" }
]
});
and in click event this code :
dataSource.read();
and in api web method this action:
[HttpGet]
public HttpResponseMessage GetData([FromUri]KendoGridParams/* define class to get parameter from javascript*/ _param)
{
// use _param to filtering, paging and other actions
try
{
var result = Service.AllCustomers();
return Request.CreateResponse(HttpStatusCode.OK, new { result = result });
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, new { result = string.Empty });
}
}
good luck.
To persist the updated value of the additional parameter through pagination, you will need to create a global variable and save the value to it.
var anotherParamValue= "";//declare a global variable at the top. Can be assigned some default value as well instead of blank
Then, when you trigger the datasource read event, you should save the value to the global variable we created earlier.
anotherParamValue = 'foo';//save the new value to the global variable
grid.dataSource.read( { anotherParam: anotherParamValue });
grid.refresh();
Now, this is important. In your datasource object transport.read.data must be set to use a function as shown below:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '/Api/GetData',
contentType: "application/json; charset=utf-8", // optional
dataType: "json",
//Must be set to use a function, to pass dynamic values of the parameter
data: function () {
return {
additionalParam: anotherParamValue //get the value from the global variable
};
}
},
},
schema: {
type: "json",
data: function (data) {
return data.result;
},
},
pageSize: 5,
serverPaging: true,
serverSorting: true
});
Now on every page button click, you should get the updated value of the anotherParam which is currently set to foo

jqGrid: Load JSON data after local data already in table

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.

Categories