How load json data by ajax call in jqgrid - ajax

By ajax call data fetched from server but problem is that response
should be load in jqgrid but not loading. In var dataAjax = jData.responseText;
dataAjax received data from server.
Whats wrong with that. please help
$(document).ready(function(){
var resData = "";
$(".btnLoad").click((function(){
resData = $.ajax({
type : "POST",
url: "/AccountUI/DataFlow/AccountDetails.html",
dataType: "json",
success: functioin(jData){
var dataAjax = jData.responseText;
return dataAjax;
}
});
});
var gridData = new Array();
gridData = resData;
jQuery("#ajgrid").jqGrid({
datatype: "json",
height: 250,
colNames:['AccID','AccName', 'AccBranch'],
colModel:[ {name:'AccID',index:'AccID', width:60, sorttype:"int"},
{name:'AccName',index:'AccName', width:90},
{name:'AccBranch',index:'AccBranch', width:100}
],
multiselect : true,
caption : "Account Grid"
});
for(var i=0;i<=gridData.length;i++)
jQuery("#ajgrid").jqGrid('addRowData',i+1,gridData[i]);
});

There are misunderstanding what datatype: "json" means. It works together with url option. jqGrid makes Ajax request for you and filled returned from the server data in the grid. If you don't implemented server side paging you should add additionally loadonce: true option to the grid.
So I hope that what you need is: 1) remove manual $.ajax call; 2) remove the loop where you fill the grid using addRowData; 3) add the following options to jqGrid:
url: "/AccountUI/DataFlow/AccountDetails.html",
mtype: "POST",
loadonce: true,
gridview: true,
autoencode: true
I recommend you additionally to replace height: 250 to height: "auto". Depend on the exact format of returned data you could need to add jsonReader with the properties which help jqGrid to interpret the server response correctly. Probably that jqGrid could automatically detect the format of returned data.

Related

Populating a kendo multiselect with ajax data

I am using a kendo multiselect widget for users to select different values pulled from the database via an ajax call. The ajax call takes one parameter, searchValue, which will narrow down the returned data. Here is my controller:
[HttpPost]
public JsonResult ProfitabilitySearch(string searchValue)
{
return Json(InventoryDataAccess.ProfitabilitySearch(searchValue));
}
1) How do you get the value from the text box to use as your searchValue? I commented the area in question below.
Here is my dataSource:
var searchDataSource = new kendo.data.DataSource({
transport: {
read: function () {
$.ajax({
type: 'POST',
url: Firm.ProfitabilitySearchURL,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
//'SuperClient' is test data to see if it works, but what do i
//need to make searchValue = what I type?
data: JSON.stringify({ searchValue: 'SuperClient'}),
success: function (data) {
return data.RESULT;
}
});
}
},
group: { field: 'category' },
serverFiltering: true
});
And here is where I create the multiselect widget:
var TKSearch = $("#TKSearch").kendoMultiSelect({
dataSource: searchDataSource,
autoBind: false,
minLength: 3,
placeholder: 'Search Timekeepers...',
dataTextField: 'label',
dataTextValue: 'value',
delay: 200
}).data("kendoMultiSelect");
I'm not sure if this will help, but here is the structure of the json that is returned from the ajax call:
{"label":"SUNFLOWER REALTY CORP. (023932)","value":"023932","category":"RC"}
Solving the first question above may answer my second question so I will wait to ask that until after.
You can use functions for the request parameters.
var searchDataSource = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: 'POST',
url: Firm.ProfitabilitySearchURL,
contentType: 'application/json; charset=utf-8',
data: {
searchValue: function () {
// better: use a model property instead of this
return $("#TKSearch").data('kendoMaskedTextBox').value();
}
},
success: function (data) {
options.success(data.RESULT);
}
});
}
},
group: { field: 'category' },
serverFiltering: true
});
Notes
This really should be a GET request. Use POST for requests that actually change data on the server and GET for requests that merely retrieve data from the server.
You do not have to JSON.stringify() yourself. jQuery does that transparently.
Specifying dataType is completely superfluous, jQuery will figure this out from the response headers.
Reading the input value via jQuery is not clean. Use the data-bound model property instead.
The callback invocation (options.success())
This sample lacks HTTP error handling, you must add that.

Client side sort not working

I have a jqgrid with the following information:
$("#Table").jqGrid({
url: 'u.json,
loadonce:true,
colNames: msd.rise.columnDisplayNames,
colModel: msd.rise.colModelDef,
gridview: true,
toppager: false,
sortname: 'sd',
sortorder: 'desc',
sortable:true,
loadComplete: function(){
$("#Table").setGridParam({datatype:'json', page:1}).trigger('reloadGrid');
}
});
The client side sort doesn't work. I put loadonce:true and $("#Table").setGridParam({datatype:'json', page:1}).trigger('reloadGrid'); based of this answer. But it still doesn't work. Any idea?
The code of loadComplete which you use currently is wrong. You should never use unconditional .trigger('reloadGrid') inside of loadComplete. Moreover the setting of datatype to 'json' before reloading will makes reloading of data from the server, but you need local reloading to apply sorting. The correct code will be like in the example from the anwer:
loadComplete: function () {
var $self = $(this);
if ($self.jqGrid("getGridParam", "datatype") === "json") {
setTimeout(function () {
$self.trigger("reloadGrid"); // Call to fix client-side sorting
}, 50);
}
}
The code makes reloading only once after the initial loading from the server will be finished.

How to delete selected rows from server and reload grid?

Im trying to implement a jqgrid in my web page but not able to handle delete; if the user selects multiple values, and clicks on delete, I want to invoke a servlet that will handle the delete and return to the page.
The code snippet is as below:
<script type="text/javascript">
function fillGridOnEvent(){
$("#jQGrid").html("<table id=\"list\"></table><div id=\"page\"></div>");
jQuery("#list").jqGrid({
url:'<%=request.getContextPath()%>/MyServletGrid?q=1&action=fetchData',
datatype: "xml",
mtype: 'POST',
height: 423,
colNames:['##','Keyword','Category','ViewType',"Action"],
colModel:[
{name:'srNo',index:'srNo', width:30,sortable:true,align:'center'},
{name:'Keyword',index:'Keyword', width:200,sortable:true},
{name:'Category',index:'Category', width:100,sortable:true,align:'center'},
{name:'ViewType',index:'ViewType', width:100,sortable:true,align:'center'},
{name:'view',index:'view', width:113,sortable:false,align:'center'}
],
multiselect: true,
paging: true,
rowNum:18,
pager: $("#page"),
loadonce:true,
caption: "Test JQGrid"
}).navGrid('#page',{edit:false,add:false,del:true});
}
jQuery().ready(function (){
//fillGrid(); rowList:[10,20,30],
});
Get the row id of the row to be deleted as follows
var rowid = jQuery("#tableid").jqGrid('getGridParam', 'selrow');
Get the row data using the following
var rowdata = jQuery("#tableid").jqGrid('getRowData', rowid);
rowdata will have your data like rowdata.srNo, rowdata.Keyword etc.,
Issue an ajax call to your servlet for the delete from your database. Then call the following to reload your grid
jQuery("#tableid").trigger('reloadGrid');

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.

How to pass extra parameter to Add and Edit url in jqGrid

Order id is stored in variable _documentId and changed in runtime by ajax call if new order is saved to actual it.
If adding new detail row to jqGrid Add form url or inline Edit url reqires this id also.
I tried to use postdata but _documentId is not passed if Edit and Add urls are called.
How to pass _documentId value to those urls ?
var _documentId; // assigned from ajax call after save.
$(function () {
var grid = $("#grid");
grid.jqGrid({
postData: {_documentId: function() { return _documentId } },
editurl: 'Edit', // How to pass _documentId value to this controller ?
url: 'GetData',
datatype: "json",
mtype: 'POST',
scroll: 1,
multiselect: true,
multiboxonly: true,
scrollingRows : true,
autoencode: true,
prmNames: {id:"_rowid", oper: "_oper" },
colModel: <%= Model.ColModel() %>,
gridview: true,
toppager: true,
viewrecords: true
});
grid.navGrid("#grid_toppager", {}, {}
{ url: 'Add' } // How to pass _documentId value to this controller ?
);
In case of form editing, you should use editData parameter to send additional data to the server. Another way is to modify the postdata inside of onclickSubmit or beforeSubmit event handler. You can of course do it in the serializeEditData event handler instead. Using onclickSubmit, you can easy modify the URL (params.url) if you need really place the information in the URL and not in the data which will be send to the server.
In case of inline editing, you can use extraparam parameter of the editRow or use serializeRowData event handler.

Resources