autocomplete not accepting the json object for source - javascript

Below is the jsp page tag for input text element:
<input name="searchTextSpan" id="searchTextSpan" type="text"/>
below is the ajax call that loads on dcument.ready:
AUI().use("liferay-portlet-url", function(A) {
var resourceURL = Liferay.PortletURL.createResourceURL();
resourceURL.setPortletId("app_war_portlet");
resourceURL.setResourceId(resourceId);
require(["dojo/request", "dijit/registry", "dojo/on", "dojo/domReady!"], function(request){
request.post(resourceURL.toString(), {
query: ajaxData,
handleAs: "json"
}).then(function(data){
if(resourceId == 'inputTextClick'){
AUI().use("liferay-portlet-url", function(A) {
var resourceURL = Liferay.PortletURL.createResourceURL();
resourceURL.setPortletId("app_war_portlet");
if(data.cachetmpArr!=null && data.cachetmpArr.length>0){
var cacheList = JSON.stringify(data.cachetmpArr);
cacheList = cacheList.replace(/"/g, "'");
console.log('cacheList12 '+cacheList);//['106182233','206182233','306182233'];
$('#searchTextSpan').autocomplete({
width: 300,
max: 10,
delay: 100,
minLength: 1,
autoFocus: true,
cacheLength: 1,
scroll: true,
highlight: false,
source:cacheList,
}).focus(function(){
$(this).autocomplete("search", "");
});
}
});
}
});
})
})
the source attribute is not accepting the cacheList it throws 404 url error.
can you please suggest

You need to parse JSON before you pass it to autocomplete.
Like this:
$('#searchTextSpan').autocomplete({
width: 300,
max: 10,
delay: 100,
minLength: 1,
autoFocus: true,
cacheLength: 1,
scroll: true,
highlight: false,
source:JSON.parse(cacheList), // parse JSON response
}).focus(function(){
$(this).autocomplete("search", "");
});

Related

How to set grid post param dynamically and trigger reload with the new URL?

I have the following jQgrid Free (version: 4.15.2) definition:
$(document).ready(function () {
var $load_form = $("#load_form"),
$form_id = sessionStorage.getItem('form_id') === null ? 1 : sessionStorage.form_id,
$questions_grid = $("#questions");
$(document).on("click", $load_form, function (ev) {
// get the new form_id value and reload the grid by passing
// the new form_id as post parameter for the AJAX request
});
$questions_grid.jqGrid({
url: '/ajax/questions/get/' + $form_id,
datatype: "json",
colNames: ['id', 'grid_id', 'seq', 'type', 'text'],
colModel: [
{name: 'field_id', index: 'id', width: 100, editable: false, editoptions: {readonly: true, size: 10}},
{name: 'grid_id', index: 'grid_id', width: 50, editable: false, editoptions: {readonly: true, size: 10}},
{name: 'field_seq', index: 'seq', width: 45, editable: true, editoptions: {size: 10}},
{name: 'type', index: 'type', width: 125, editable: false, editoptions: {readonly: true, size: 10}},
{
name: 'field_name',
index: 'text',
width: 585,
editable: true,
edittype: "textarea",
editoptions: {rows: "5", cols: "45"}
}
],
autowidth: true,
iconSet: "fontAwesome",
rowNum: 100,
guiStyle: "bootstrap",
pager: 'questions_pager',
pgbuttons: false,
pginput: false,
sortname: 'seq',
viewrecords: true,
caption: "Questions",
width: 100,
height: "auto",
editurl: 'ajax/questions/edit',
multiselect: true,
subGrid: false,
subGridUrl: 'ajax/questions/get_options',
subGridModel: [{name: ['id', 'text', 'is required'], width: [55, 200, 20]}],
gridComplete: function () {
// Don't need the +1 because it includes ".jqgfirstrow"
var seq_number = this.rows.length;
$("#next_seq_num").val(seq_number);
$("#field_seq").empty();
$("#grid_field_seq").empty();
for (var i = 1; i <= seq_number; i++) {
var sel = (i == seq_number) ? 'selected' : null;
$("#field_seq").append("<option " + sel + ">" + i + "</option>");
$("#grid_field_seq").append("<option " + sel + ">" + i + "</option>");
}
$(window).trigger('resize');
},
onSelectRow: function (ids) {
if (ids !== null) {
$("#option_field_id").val(ids);
$(".field_seq_section").hide();
$.ajax({
type: "POST",
url: "ajax/questions/get_grid_example/" + ids,
success: function (msg) {
if (msg !== "") {
jQuery('#options_ids').empty();
}
jQuery('#grid_cells_example').html(msg);
}
});
edit_question("<?php echo site_url('ajax/questions/get_by_id') ?>/" + ids, false);
}
}
}).jqGrid('hideCol', 'cb');
});
At some point and dynamically I am setting the value of the property data-formid for $("#load_form"). Since $("#load_form") is a button (see definition below) I would like to trigger the reloadGrid event using the new $formid value so I get a new fresh data from the DB.
<button type="submit" class="btn btn-default" data-formid="" id="load_form">
Load form
</button>
In a few logical steps:
Set the value for data-formid
Click on the button
Trigger reloadGrid with $("#load_form").data("formid")
I have found this: how to set postData in jqgrid AFTER it has been constructed? but I am not sure how to apply on my scenerio.
How I can achieve this?
If I understand you correctly you want to change url parameter. The code of the click-event handler could be close to the following:
$(document).on("click", $load_form, function (ev) {
var p = $questions_grid.jqGrid("getGridParam");
p.url = "/ajax/questions/get/" + $("#load_form").data("formid");
$questions_grid.trigger("reloadGrid");
});

Add/edit/delete a row in free jqGrid

I am using free jqGrid 4.12.1. I want to add, edit and delete rows in the grid and wish to make server side calls for each operation.
I have added editurl and 'actions' formatter as below,
{
name: "actions",
width: 100,
formatter: "actions",
formatoptions: {
keys: true,
editOptions: {},
addOptions: {},
delOptions: {}
}
}
I am adding 'inlineNav' as below,
$("#itemList").jqGrid('inlineNav',"#itemListPager",
{
edit: true,
add: true,
del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete"
},
{
closeOnEscape: true, //Closes the popup on pressing escape key
reloadAfterSubmit: true,
drag: true,
url: "${pageContext.request.contextPath}/billing/saveItem",
errorfunc: function (rowId, resp) {
alert(resp);
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after edit
return [true, '']
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after edit
return [false, response.responseText]//Captures and displays the response text on th Edit window
}
},
editData: {
EmpId: function () {
var sel_id = $('#itemList').jqGrid('getGridParam', 'selrow');
var value = $('#itemList').jqGrid('getCell', sel_id, '_id');
return value;
}
}
},
{
closeAfterAdd: true, //Closes the add window after add
url: "${pageContext.request.contextPath}/billing/saveItem",
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')//Reloads the grid after Add
return [true, '']
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')//Reloads the grid after Add
return [false, response.responseText]
}
}
},
{ //DELETE
closeOnEscape: true,
closeAfterDelete: true,
reloadAfterSubmit: true,
url: "${pageContext.request.contextPath}/billing/saveItem",
drag: true,
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$("#itemList").trigger("reloadGrid", [{ current: true}]);
return [false, response.responseText]
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
return [true, response.responseText]
}
},
delData: {
EmpId: function () {
var sel_id = $('#itemList').jqGrid('getGridParam', 'selrow');
var value = $('#itemList').jqGrid('getCell', sel_id, '_id');
return value;
}
}
},
{//SEARCH
closeOnEscape: true
}
);
The 'inlineNav' added above has no effect because no server side call is made on adding a new row or deleting existing row. The server side call is made only in case of edit, and that call too does not happen through 'inlineNav' code above. Because even if i remove 'inlineNav' code the server side call is still made to the 'editurl'.
So how can i make server side calls on adding/editing/deleting rows and also pass parameters to these calls. I will really appreciate if someone can point me to a working example somewhere. Thanks
UPDATE:-
I have removed 'actions' formatter and modified code to look as below,
<script type="text/javascript">
var dataGrid = $('#itemList');
var firstClick = true;
$(document).ready(function () {
$('#action').click(function () {
if (!firstClick) {
$("#itemList").setGridParam({datatype:'json'}).trigger("reloadGrid");
}
firstClick = false;
$("#itemList").jqGrid({
url: "${pageContext.request.contextPath}/billing/medicines",
datatype: "json",
//styleUI : 'Bootstrap',
mtype: "POST",
autowidth: true,
shrinkToFit: true,
sortname: "Id",
sortorder: "asc",
loadBeforeSend: function(jqXHR) {
jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val());
},
postData: {
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
},
colNames: ["Id", "Item Type", "Item Code", "Unit", "Stock", "Batch No.", "Expiry Date", "Quantity Per Unit", "Price"],
colModel: [
{ name: "itemId", width: 35, align: "left", sorttype:"int", search: false},
{ name: "itemType", width: 100, align: "left", editable: true},
{ name: "itemCode", width: 120, align: "left", editable: true},
{ name: "unit", width: 70, align: "left", search: false, editable: true},
{ name: "availableQuantity", width: 55, align: "left", search: false, formatter: "number", editable: true},
{ name: "batchNumber", width: 80, align: "left", search: false, editable: true},
{ name: "expiryDate", width: 80, align: "left", search: false, sorttype: "date", editable: true, formatoptions: {srcformat:'d/m/Y', newformat:'d/m/Y'}},
{ name: "quantityPerUnit", width: 80, align: "left", search: false, formatter: "number", editable: true},
{ name: "price", width: 55, align: "left", search: false, formatter: "number", editable: true}
],
pager: "#itemListPager",
rowNum: 50,
rowList: [50, 100, 150, 200],
rownumbers: true,
rownumWidth: 25,
sortname: "id",
sortorder: "desc",
viewrecords: true,
height: '100%',
loadonce: true,
//gridview: true,
autoencode: true,
editurl: "${pageContext.request.contextPath}/billing/saveItem",
caption: "Item List",
ondblClickRow: function(rowId){}
}).navGrid('#itemListPager',{add:false,edit:false,del:true});
$("#itemList").jqGrid('filterToolbar', {autoSearch: true, stringResult: true, searchOnEnter: false, defaultSearch: 'cn'});
$("#itemList").jqGrid('gridResize', { minWidth: 450, minHeight: 150 });
var saveparameters = {
"successfunc" : null,
"url" : "${pageContext.request.contextPath}/billing/saveItem",
"extraparam" : {},
"aftersavefunc" : null,
"errorfunc": null,
"afterrestorefunc" : null,
"restoreAfterError" : true,
"mtype" : "POST"
};
var editparameters = {
"keys" : false,
"oneditfunc" : null,
"successfunc" : null,
"url" : "${pageContext.request.contextPath}/billing/editItem",
"extraparam" : {},
"aftersavefunc" : null,
"errorfunc": null,
"afterrestorefunc" : null,
"restoreAfterError" : true,
"mtype" : "POST"
};
var parameters = {
edit: true,
editicon: "ui-icon-pencil",
add: true,
addicon:"ui-icon-plus",
save: true,
saveicon:"ui-icon-disk",
cancel: true,
cancelicon:"ui-icon-cancel",
addParams : saveparameters,
editParams : editparameters
};
$("#itemList").jqGrid('inlineNav',"#itemListPager", parameters);
});
});
</script>
The sample json dada is as,
[
{"itemDetailId":1,"itemId":1,"itemType":"Medicine","itemCode":"Aler-Dryl","itemDesc":"Aler-Dryl","batchNumber":"batch1","expiryDate":"18/02/2017","unit":"tablet","subUnit":"tablet","availableQuantity":120.0,"quantityPerUnit":60.0,"price":122.0},
{"itemDetailId":2,"itemId":2,"itemType":"Medicine","itemCode":"Benadryl","itemDesc":"Benadryl","batchNumber":"batch1","expiryDate":"18/02/2017","unit":"ml","subUnit":"ml","availableQuantity":60.0,"quantityPerUnit":120.0,"price":90.0}
]
Now the url specified in editparameters and saveparameters is getting invoked on editing and adding a row respectively.
Please suggest if above approach is a good one. Also how can we set a request header before edit or save data is posted to server. And i can not find anything like deleteparameters similar to editparameters and saveparameters so that i can use delete specific parameters.
UPDATE 2:-
I could successfully set a request header before server side code is invoked on add/edit row using following code,
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val());
}});
UPDATE 3:-
Cleaned up code as per Oleg's suggestions as below. But in the strict mode i am getting JS error now - "Uncaught ReferenceError: saveparameters is not defined"
<script type="text/javascript">
$(document).ready(function () {
"use strict";
var dataGrid = $('#itemList');
var firstClick = true;
$('#action').click(function () {
if (!firstClick) {
$("#itemList").setGridParam({datatype:'json'}).trigger("reloadGrid");
}
firstClick = false;
$("#itemList").jqGrid({
url: "${pageContext.request.contextPath}/billing/medicines",
datatype: "json",
mtype: "POST",
autowidth: true,
loadBeforeSend: function(jqXHR) {
jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val());
},
colNames: ["Id", "Item Type", "Item Code", "Unit", "Stock", "Batch No.", "Expiry Date", "Quantity Per Unit", "Price"],
colModel: [
{ name: "itemId", width: 35, align: "left", sorttype:"int", search: false, editable: false, key: true},
{ name: "itemType", width: 100, align: "left"},
{ name: "itemCode", width: 120, align: "left"},
{ name: "unit", width: 70, align: "left", search: false},
{ name: "availableQuantity", width: 55, align: "left", search: false, formatter: "number",},
{ name: "batchNumber", width: 80, align: "left", search: false},
{ name: "expiryDate", width: 80, align: "left", search: false, sorttype: "date", formatoptions: {srcformat:'d/m/Y', newformat:'d/m/Y'}},
{ name: "quantityPerUnit", width: 80, align: "left", search: false, formatter: "number"},
{ name: "price", width: 55, align: "left", search: false, formatter: "number"}
],
cmTemplate: {editable: true},
pager: true,
rowNum: 50,
rowList: [50, 100, 150, 200],
rownumbers: true,
rownumWidth: 25,
sortname: "itemType",
sortorder: "asc",
forceClientSorting: true,
viewrecords: true,
height: '100%',
loadonce: true,
//gridview: true,
autoencode: true,
editurl: "${pageContext.request.contextPath}/billing/saveItem",
caption: "Item List"
//ajaxRowOptions: { beforeSend: myTokenSetting }, loadBeforeSend: myTokenSetting where var myTokenSetting = function(jqXHR) { jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val()); }
}).navGrid({add:false,edit:false,del:true});
$("#itemList").jqGrid('filterToolbar', {autoSearch: true, stringResult: true, searchOnEnter: false, defaultSearch: 'cn'});
$("#itemList").jqGrid('gridResize', { minWidth: 450, minHeight: 150 });
var saveparameters = {
"successfunc" : null,
"url" : "${pageContext.request.contextPath}/billing/saveItem",
"extraparam" : {},
"aftersavefunc" : null,
"errorfunc": null,
"afterrestorefunc" : null,
"restoreAfterError" : true,
"mtype" : "POST"
};
var editparameters = {
"keys" : false,
"oneditfunc" : null,
"successfunc" : null,
"url" : "${pageContext.request.contextPath}/billing/editItem",
"extraparam" : {},
"aftersavefunc" : null,
"errorfunc": null,
"afterrestorefunc" : null,
"restoreAfterError" : true,
"mtype" : "POST"
};
var parameters = {
edit: true,
editicon: "ui-icon-pencil",
add: true,
addicon:"ui-icon-plus",
save: true,
saveicon:"ui-icon-disk",
cancel: true,
cancelicon:"ui-icon-cancel",
addParams : saveparameters,
editParams : editparameters
};
$("#itemList").jqGrid('inlineNav',parameters);
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
alert('Before Row Send');
jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val());
}});
});
});
</script>
You should examine the options of inlineNav to find out that you use absolutely wrong options:
jQuery("#grid_id").jqGrid('inlineNav', pagerid, parameters);
where parameters have the form
{
edit: true,
editicon: "ui-icon-pencil",
add: true,
addicon: "ui-icon-plus",
save: true,
saveicon: "ui-icon-disk",
cancel: true,
cancelicon: "ui-icon-cancel",
addParams: {useFormatter : false},
editParams: {}
}
You use the options of another method navGrid
jQuery("#grid_id").jqGrid('navGrid', '#gridpager', {parameters},
prmEdit, prmAdd, prmDel, prmSearch, prmView);
which allows to use form editing.
You wrote that you want to use both formater: "actions" andinlineNav. Thus you would have to provide some options of inline editing twice. I would recommend you to read [the wiki article](https://github.com/free-jqgrid/jqGrid/wiki/New-style-of-usage-options-of-internal-methods). It describes the problems with the usage of form editing usingformatter: "actions"andnavGridtogether. The usage of inline editing have very close problems. You will have to provideaddParamsandeditParamsproperties ofinlineNavand the corresponding options offormatter: "actions"` (see here). To make the code more readable and simple free jqGrid provides another form of editing options.
You can specify all inline editing options inside of inlineEditing option of jqGrid, additional specific options of inlineNav method (if required) in navOptions or in inlineNavOptions, the options of Delete operation in formDeleting and so on. Moreover reloadGrid have the option fromServer: true to restore the original value of datatype ("json", "jsonp", "xml", ...) which you used. You can use reloadGridOptions: { fromServer: true } option of form editing or formDeleting to force reloading from the server.
Moreover your existing code contains many very suspected parts with _id and EmpId. I would strictly recommend you to include the example of format of input JSON data which you use to fill the grid. If you want to use EmpId as the name of rowid why you use _id instead? The code fragment like
EmpId: function () {
var sel_id = $('#itemList').jqGrid('getGridParam', 'selrow');
var value = $('#itemList').jqGrid('getCell', sel_id, '_id');
return value;
}
shows that the current rowid seems be wrong and _id column contains correct information which you need as rowid under the name EmpId.
You can for example use prmNames: { id: "EmpId"} and to add key: true to the column _id. The property key: true in the column _id will inform jqGrid to use the value from the column _id as the rowid and prmNames: { id: "EmpId"} will rename default id property used in Edit and Delete to EmpId. Thus jqGrid will automatically send EmpId parameter with the value from _id column during Delete and Edit operations to the server.
Probably you can remove unneeded column _id from the grid too (at least if you hold the column hidden), but I need to see input data of jqGrid to say you exact options of jqGrid which you can use.
I'm sure that you can essentially reduce your existing code and make it more readable using free jqGrid options, but you have to review your existing code carefully. I suggest you to start with the usage of correct rowid and elimination of all hidden columns which you use. Free jqGrid provides additionalProperties feature which structure is very close to the structure of colModel, but the corresponding properties of input data will be saved in the local data only and not placed in DOM of the table. I can explain all more clear if you would post your existing colModel, jsonReader and example of JSON response returned from the server (1-2 rows of data with dummy data would be enough).

Iframe not rendering contents second time

I am rendering partial view though ajax in Iframe of Main View. And it works fine locally but after publish its works only first time second time it clears iframe body
Here is My Code:
$('#editFaxdialog').dialog({
autoOpen: false,
title: 'Edit PDF',
height: 'auto',
width: '80%',
position: ['top', 50],
draggable: false,
show: 'blind',
hide: 'blind',
modal: true,
open: function (event, ui) {
$.ajax({
url: '#Url.Action("EditPdf", "Fax")',
type: 'GET',
cache:false,
success: function(data){
var frameSet = document.getElementById("editFaxFrame");
var iframedoc = frameSet.document;
if (frameSet.contentDocument)
iframedoc = frameSet.contentDocument;
else if (frameSet.contentWindow)
iframedoc = frameSet.contentWindow.document;
if (iframedoc){
iframedoc.open();
iframedoc.writeln(data);
iframedoc.close();
}
},
error: function () {
window.location.href = '#Url.Action("Index","Error")';
}
});
},
close: function (event, ui) {
$("#editFaxFrame").attr("src", '');
}
});
I solved This Issue after so much r&d i put Settimeout() function on ajax success
$('#editFaxdialog').dialog({
autoOpen: false,
title: 'Edit PDF',
height: 'auto',
width: '80%',
position: ['top', 50],
draggable: false,
show: 'blind',
hide: 'blind',
modal: true,
open: function (event, ui) {
$.ajax({
url: '#Url.Action("EditPdf", "Fax")',
type: 'GET',
cache:false,
success: function(data){
setTimeout(function () {
var frameSet = document.getElementById("editFaxFrame");
var iframedoc = frameSet.document;
if (frameSet.contentDocument)
iframedoc = frameSet.contentDocument;
else if (frameSet.contentWindow)
iframedoc = frameSet.contentWindow.document;
if (iframedoc){
iframedoc.open();
iframedoc.writeln(data);
iframedoc.close();
}
},400);
},
error: function () {
window.location.href = '#Url.Action("Index","Error")';
}
});
},
close: function (event, ui) {
$("#editFaxFrame").attr("src", '');
}
});

Object doesn't support property or method 'jqGrid' on windows server 2012

the jq grid is running fine on asp.net dev server but on IIS 8 (Windows Server 2012) it is giving the following error: Object doesn't support property or method 'jqGrid'
JS
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('#GridList').jqGrid({
autoencode: true,
autowidth: true,
caption: 'List',
cmTemplate: { sortable: false },
datatype: 'json',
jsonReader: { 'repeatitems': false, 'id': 'Id' },
emptyrecords: 'No record Found',
multiselect: true,
gridview: true,
recordpos: 'left',
height: '100%',
loadui: 'block',
pager: '#pager',
rowList: [10, 15, 20, 50],
rowNum: 10,
viewsortcols: [true, 'vertical', true],
shrinkToFit: true,
url: '#Url.Action("List")',
viewrecords: true,
width: '650',
colModel: [
#Html.GetGridColumn(model => model.Id),
#Html.GetGridColumn(model => model.ResultId),
#Html.GetGridColumn(model => model.HostReference),
#Html.GetGridColumn(model => model.FirstName),
#Html.GetGridColumn(model => model.LastName),
#Html.GetGridColumn(model => model.UserID)
]
});
//jQuery('#GridList').jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false });
jQuery("#GridList").navGrid('#pager', { edit: false, add: false, del: false });
jQuery("#btnSubmit").click(function () {
var s;
s = jQuery("#GridList").jqGrid('getGridParam', 'selarrrow');
alert(s);
});
});
</script>
Update:
this is how i call the list:
protected ActionResult List(GridSettings grid)
{
var query = ListQuery.AsQueryable().OrderBy(grid.SortColumn, grid.SortOrder);
if (grid.IsSearch && grid.Where != null && grid.Where.rules != null)
{
query = grid.Where.rules.Aggregate(query,
(current, rule) => current.Where(rule.field, rule.data, rule.op));
}
var count = query.Count();
var data = query.Skip((grid.PageIndex - 1) * grid.PageSize)
.Take(grid.PageSize)
.Select(Mapper.Map<TModel, TListModel>);
// TO DO: Prevent GridDataType.NoDisplay fields from being
// serialised
var result = new
{
total = (int)Math.Ceiling((double)count / grid.PageSize),
page = grid.PageIndex,
records = count,
rows = data.ToArray()
};
var serialiser = new JavaScriptSerializer();
serialiser.MaxJsonLength = int.MaxValue;
//serialiser.RegisterConverters(new[] { new SingleSelectConverter() });
//serialiser.RegisterConverters(new[] { new MultiSelectConverter() });
var jsonString = serialiser.Serialize(result);
return new ContentResult { Content = jsonString, ContentType = "application/json"};
}
What seems that you have issue of reference, just check the jqgrid library path whether that is referenced properly or not.
or may be you could have forgot to reference the library with all other required library.
some side notes:
Since you are using dataType:"json" and i can see that you have not used loadonce: true option in the list which is required when dataType is "json" and you have mentioned your column names, try including those too.:
jQuery('#GridList').jqGrid({
autoencode: true,
autowidth: true,
caption: 'List',
cmTemplate: { sortable: false },
datatype: 'json',
........
loadonce: true
});
Finally i found my answer, i was using third party dll, it's in dll folder, when i depolyed, i had to add to bin folder as well...Thank you for the help

jqGrid send edited/delete inline information serialized JSON format

I'm trying to do an inline edit with a column with formatter: 'actions' and want to send the information to the server in JSON format, but I cant. I already tried many things, but with no results. Still sending information without serializing.
Also tried $.extend($.jgrid.edit, (...)); at the initialization $(function(){...}); with no result.
My formatoptions looks like this:
formatoptions: {
keys: true,
editbutton: true,
delbutton: true,
//url: url,
editOptions: {
url: url,
ajaxEditOptions: {
//url: url,
contentType: 'application/json;charset=utf-8',
type: 'POST',
datatype: 'json'
}
},
delOptions: {
url: url,
ajaxDelOptions: {
//url: url,
contentType: 'application/json;charset=utf-8',
type: 'POST',
datatype: 'json'
}
}
}}
But still not working :S I dont know what im doing wrong.
I'd appreciate if you help me.
PS: I writted too many url properties, becuase I was checking where I have to write it to do it work. For edit, only works if I put the url out of editOptions, only if I put it in formatoptions. But for delete, it don't cares if I put it in/out delOptions, including ajaxDelOptions. If you could help me with that too, I'd appreciate.
UPDATED
Delete works fine with this config, but inline editing save button still not working. I pasted the same config, changing options for editing and still not working.
delOptions: {
url: url,
mtype: 'POST',
reloadAfterSubmit: true,
ajaxDelOptions: {
contentType: "application/json"
},
serializeDelData: function(postdata) {
return JSON.stringify(postdata);
}
}
UPDATED 2
Here is my JS.
$(function() {
$.mask.definitions['2'] = '[0-2]';
$.mask.definitions['5'] = '[0-5]';
$.extend($.jgrid.defaults, {
ajaxRowOptions: {
contentType: "application/json",
dataType: "json",
success: function() {
},
error: null
},
serializeRowData: function(data) {
delete data.oper;
return JSON.stringify(data);
}
});
});
function loadGrid(identifier) {
$("#list").jqGrid({
url: 'foo.html?identifier=' + identifier,
type: 'GET',
datatype: 'json',
repeatitems: false,
autowidth: true,
altRows: false,
hidegrid: false,
cmTemplate: {
sortable: false,
resizable: false
},
colNames: ["id", "column1", "column2", "column3", "column4", "column5", "column6", "column7", " "],
colModel: [
{name: "id", label: "id", hidden: true},
{name: "columnData1", label: "columnData1", key: true, hidden: true},
{name: "columnData2", label: "columnData2", edittype: "select", editable: true,
editoptions: {
dataUrl: 'foo/bar.html'
}},
{name: "columnData3", label: "columnData3", width: 75, editable: true},
{name: "columnData4", label: "columnData4", width: 100, edittype: "select", editable: true,
editoptions: {
dataUrl: 'foo/bar.html'
}},
{name: "columnData5", align: "right", label: "columnData5", width: 55, formatter: 'number',
formatOptions: {
decimalPlaces: 2
}, editable: true},
{name: "columnData6", align: "right", label: "columnData6", width: 55, formatter: 'number',
formatOptions: {
decimalPlaces: 2
}, editable: true},
{name: "columnData7", align: "right", label: "columnData7", width: 55, formatter: 'number',
formatOptions: {
decimalPlaces: 2
}},
{name: "actions", formatter: "actions", width: 35}
],
pager: '#pager',
rows: '',
rowList: [],
pgbuttons: false,
pgtext: null,
viewrecords: false,
gridview: true,
caption: 'MyCaption',
subGrid: true,
subGridRowExpanded: function(subgrid_id, row_id) {
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id + "_t";
pager_id = "p_" + subgrid_table_id;
$("#" + subgrid_id).html("<table id='" + subgrid_table_id + "'></table><div id='" + pager_id + "'></div>");
$("#" + subgrid_table_id).jqGrid({
url: 'foo/bar.html?identifier=' + identifier + '&rowId=' + row_id,
type: 'GET',
datatype: 'json',
repeatitems: false,
autowidth: true,
altRows: false,
hidegrid: false,
cmTemplate: {
sortable: false,
resizable: false
},
colNames: ['column1', 'column2', 'column3', 'column4', 'column5', 'column6', ' '],
colModel: [
{name: 'columnData1', hidden: true, key: true},
{name: 'columnData2', width: 75, formatter: 'date',
formatoptions: {
srcformat: 'Y-m-d',
newformat: 'd/m/Y'
},
editoptions: {
readonly: 'readonly',
dataInit: function(elem) {
$(elem).width("75%");
$(elem).datepicker({
dateFormat: "dd/mm/yy",
showOn: "button",
buttonImage: "../css/images/calendar.gif",
buttonText: "Muestra el calendario.",
buttonImageOnly: true
});
}}
, editable: true},
{name: 'columnData3', width: 75,
formatter: function(cellval, opts) {
if (!/^([0-1][0-9]|2[0-3]:[0-5][0-9])/.test(cellval)) {
var date = new Date(cellval);
opts = $.extend({}, $.jgrid.formatter.date, opts);
return $.fmatter.util.DateFormat("", date, 'H:i', opts);
} else {
var date = new Date();
var time = cellval.split(":");
date.setFullYear(1899);
date.setMonth(12);
date.setDate(30);
date.setHours(time[0]);
date.setMinutes(time[1]);
date.setSeconds(0);
opts = $.extend({}, $.jgrid.formatter.date, opts);
return $.fmatter.util.DateFormat("", date, 'H:i', opts);
}
},
editoptions: {dataInit: function(elem) {
$(elem).mask("29:59");
}},
editrules: {custom: true, custom_func: function(value) {
if (/^([0-1][0-9]|2[0-3]:[0-5][0-9])/.test(value)) {
return [true, ""];
} else {
return [false, " no es un formato de hora válido.<br/>Por favor, introduzca una hora en un formato <b>hh:mm</b> válido."];
}
}}, editable: true},
{name: 'columnData4', width: 80, editable: true},
{name: 'columnData5', width: 200, editable: true},
{name: 'columnData6', align: 'right', width: 50, editable: true, formatter: 'number',
formatoptions: {
decimalPlaces: 2
}},
{name: 'actions', formatter: 'actions', width: 40,
formatoptions: {
//keys: false,
editbutton: true,
delbutton: true,
url: "foo/bar/edit.html?identifier=" + identifier + "&rowId=" + row_id,
editOptions: {
keys: true,
//url: "foo/bar/edit.html?identifier=" + identifier + "&rowId=" + row_id,
mtype: "POST"
},
delOptions: {
url: "foo/bar/delete.html?identifier=" + identifier + "&rowId=" + row_id,
mtype: 'POST',
reloadAfterSubmit: true,
ajaxDelOptions: {
contentType: "application/json"
},
serializeDelData: function(postdata) {
delete postdata.oper;
return JSON.stringify(postdata);
}
}
}}
],
height: 190,
pager: pager_id,
rows: '',
rowList: [],
pgbuttons: false,
pgtext: null,
viewrecords: false,
gridview: true,
loadError: function(xhr, status, error) {
alert(xhr + " : " + status + " : " + error);
},
jsonReader: {
repeatitems: false
},
gridComplete: function() {
$("div.ui-inline-save").click(function() {
var dlgDiv = $("#info_dialog");
dlgDiv.width(600);
var parentDiv = dlgDiv.parent();
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
dlgDiv.css('top', Math.round((parentHeight - dlgHeight) / 2));
dlgDiv.css('left', Math.round((parentWidth - dlgWidth) / 2));
});
$("div.ui-inline-del").click(function() {
var dlgDiv = $("#delmod" + subgrid_table_id);
dlgDiv.width(600);
var parentDiv = dlgDiv.parent();
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
dlgDiv.css('top', Math.round((parentHeight - dlgHeight) / 2));
dlgDiv.css('left', Math.round((parentWidth - dlgWidth) / 2));
});
$("#gbox_" + subgrid_id + "_t").removeClass('ui-corner-all');
$("#" + pager_id).removeClass('ui-corner-bottom');
disableSelection(document.getElementById(subgrid_table_id));
}
}).navGrid("#" + pager_id, {add: true, edit: false, del: false, search: false, view: false, refresh: true}, {},
{afterShowForm: function(form) {
var dlgDiv = $("#editmod" + subgrid_table_id);
dlgDiv.width(600);
var parentDiv = dlgDiv.parent();
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
dlgDiv.css('top', Math.round((parentHeight - dlgHeight) / 2));
dlgDiv.css('left', Math.round((parentWidth - dlgWidth) / 2));
}
});
},
loadError: function(xhr, status, error) {
alert(xhr + " : " + status + " : " + error);
},
jsonReader: {
repeatitems: false
},
gridComplete: function() {
$("div.ui-inline-save").click(function() {
var dlgDiv = $("#info_dialog");
dlgDiv.width(600);
var parentDiv = dlgDiv.parent();
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
dlgDiv.css('top', Math.round((parentHeight - dlgHeight) / 2));
dlgDiv.css('left', Math.round((parentWidth - dlgWidth) / 2));
});
$("div.ui-inline-del").click(function() {
var dlgDiv = $("#delmodlist");
dlgDiv.width(600);
var parentDiv = dlgDiv.parent();
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
dlgDiv.css('top', Math.round((parentHeight - dlgHeight) / 2));
dlgDiv.css('left', Math.round((parentWidth - dlgWidth) / 2));
});
disableSelection(document.getElementById("list"));
}
}).navGrid("#pager", {add: true, edit: false, del: false, search: false, view: false, refresh: true}, {},
{afterShowForm: function(form) {
var dlgDiv = $("#editmodlist");
dlgDiv.width(600);
var parentDiv = dlgDiv.parent();
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
dlgDiv.css('top', Math.round((parentHeight - dlgHeight) / 2));
dlgDiv.css('left', Math.round((parentWidth - dlgWidth) / 2));
}
});
var height = $("body").height();
$('.ui-jqgrid-bdiv').height(height);
}
Changed column names, etc. for security (obviusly). This is my JS. I had to use jqGrid in a function and getting identifier as parameter, because I have a JSP that is loaded into a Iframe and that JSP has another Iframe that loads this JS. I needed to send the identifier that I recieve in the JSP to build the grid. The best way I found is that.
Thats the identifier value.
Also, I need that identifier and the row_id to update data, because I have as 3 primary keys to identify an specific item. I need identifier, parent row_id and actual row_id that I'm editing. Last one I get it from the JS Object in JSON format.
It's like it does not recognize editOptions property, because it does not get keys: true. It didn't let me accept the edit with Enter key.
If you still needing more information, just ask.
I think that the origin of your problem is misunderstanding about how formatter: 'actions' works.
There are tree main editing mode supported by jqGrid: inline editing, form editing and cell editing. If you don't use editformbutton: true option of formatter: 'actions' inside of formatoptions then Edit button will use inline editing. Delete button uses always form editing because there are no delete method in the inline editing module.
So if you includes some option inside of editOptions of formatoptions of formatter: 'actions' then it should be an option of editRow (see properties of editparameters object in the documentation). So you can specify for example
editOptions: {
url: url,
mtype: "POST", // is already default and can be removed
keys: true
}
but the ajaxEditOptions will be ignored here. $.jgrid.edit can be used to change default values for editGridRow which is part of forme editing, but to change defaults of editRow you need use $.jgrid.inlineEdit instead.
delOptions allows you specify parameters of delGridRow. The UPDATED part of your question uses correct options. So Delete operation works correctly.
By the way you can use editurl option of jqGrid to specify URL used for both inline editing and form editing. So editurl: url on one place will be better as specifying url: url multiple times.
What you need to do for successful editing is adding ajaxRowOptions and serializeRowData as jqGrid options
ajaxRowOptions: { contentType: "application/json", dataType: "json" },
serializeRowData: function (data) { return JSON.stringify(data); }
or to set it in $.jgrid.defaults.
UPDATED: You misunderstand the value of unique id. HTML standard don't allows to have two elements with the same id attribute on the page. The demo which you posed don't use idPrefix in subgrids. If you opens subgrids for who rows and examine HTML code of the page with respect of Developer Tools (press F12 in IE) you will see the following
So you have to use idPrefix for subgrids. I recommend you to use the value which depends on rowid of the parent grid (something like idPrefix: "s_" + row_id + "_"). Look at here for more my answer about the subject.
UPDATED 2: I looked in the code of formatter: "actions" one more time and I see that it uses url option of formatter for inline editing operations (see the documentation) and uses delOptions for delete and editOptions for form editing. So editOptions.url will be used only if you would use editformbutton: true option.

Categories

Resources