jqGrid: How To Delete Row/s From "navButtonAdd" And "delGridRow"? - datagrid

I've encountered a problem with jqGrid datagrid.
I need to delete one row or more with a button "Delete".
Here my code:
$grid.navGrid('#pager', { edit: false, add: false, del: false, search: false });
$grid.navButtonAdd('#pager', {
caption: "Delete",
buttonicon: "ui-icon-del",
position: "last",
onClickButton: function() {
alert("Deleting Row");
row_ids = $grid.getGridParam('selarrrow');
$grid.delGridRow(row_ids, {
dataType: 'json',
mtype: 'GET',
url: '<?php echo $_SERVER['PHP_SELF'].'?app=my_app&action=record_delete'; ?>'
});
}
});
This snippet of code send to the "url:" option the id/s of selected row/s (it works).
That url return a response, in json format.. This answer say if the operation was successful or not.
I need to display an alert with that message, how do I do?
And, another problem, when I click on "Delete" button (on bottom of the jqGrid), it displays an ajax windows with the question "Do you want to delete selected items?", with the "Yes" input and the "No" input. When I click "Yes", this ajax window will not close!
Thank you!
Dante
EDIT [1] && [2]
$(document).ready(function()
{
$grid = $("#list");
fixPositionsOfFrozenDivs = function() {
if (typeof this.grid.fbDiv !== "undefined") {
$(this.grid.fbDiv).css($(this.grid.bDiv).position());
}
if (typeof this.grid.fhDiv !== "undefined") {
$(this.grid.fhDiv).css($(this.grid.hDiv).position());
}
};
$grid.jqGrid({
url: '<?php echo $_SERVER['PHP_SELF'].'?app=my_app&option=get_records'; ?>',
datatype: 'json',
mtype: 'GET',
height: 'auto',
width: window.innerWidth-35, //width: '1225',
colNames: ['ID', 'Column A', 'Column B', 'Column C', 'Column D'],
colModel: [
{ name: 'id', index: 'id', width: 130, align: 'center', search: true,
sortable: true, frozen: true, editable: true, edittype: 'text', formatter: 'showlink',
editoptions: { size: 130, maxlength: 50 }, stype: 'text' },
{ name: 'col_a', index: 'col_a', width: 250, align: 'left', search: true,
sortable: true, frozen: false, editable: true, edittype: 'text',
editoptions: { size: 250, maxlength: 40 }, stype: 'text' },
{ name: 'col_b', index: 'col_b', width: 120, align: 'left', search: true,
sortable: true, frozen: false, editable: true, edittype: 'text',
editoptions: { size: 120, maxlength: 40 }, stype: 'text' },
{ name: 'col_c', index: 'col_c', width: 100, align: 'right', search: true,
sortable: true, frozen: false, editable: true, edittype: 'text',
editoptions: { size: 100, maxlength: 40 }, stype: 'text' },
{ name: 'col_d', index: 'col_d', width: 100, align: 'right', search: true,
sortable: true, frozen: false, editable: true, edittype: 'text',
editoptions: { size: 100, maxlength: 6 }, stype: 'text' }
],
caption: 'Objects',
pager: '#pager',
sortname: 'id',
sortorder: 'ASC',
rowNum: 25,
rowList: [25, 50, 100, 200, <?php echo $totrecords; ?>],
loadonce: true,
gridview: true,
viewrecords: true,
rownumbers: true,
rownumWidth: 40,
toppager: true,
multiselect: true,
autoencode: true,
ignoreCase: true,
shrinkToFit: false,
loadComplete: function() {
$("option[value=<?php echo $totrecords; ?>]").text('All');
},
editurl: '<?php echo $_SERVER['PHP_SELF'].'?app=my_app&option=delete_records'; ?>'
});
$grid.jqGrid('filterToolbar', {multipleSearch: false, stringResult: false, searchOnEnter: false, defaultSearch: 'cn'});
$grid.navGrid('#pager', { edit: false, add: false, del: false, search: false });
$grid.navButtonAdd('#pager', {
caption: "Delete",
buttonicon: "ui-icon-del",
position: "last",
onClickButton: function() {
row_ids = $grid.getGridParam('selarrrow');
$grid.delGridRow(row_ids, {
closeOnEscape: true,
mtype: 'POST',
afterSubmit: function(data_from_server, array_data) {
var result = data_from_server.responseText;
var message = eval('(' + result + ')');
alert(message.query);
}
});
}
});
$grid.jqGrid('setFrozenColumns');
$grid[0].p._complete.call($grid[0]);
fixPositionsOfFrozenDivs.call($grid[0]);
});

You should be able to use the afterSubmit event to display your message. From the jqGrid documentation:
afterSubmit
fires after response has been received from server. Typically used to display status from server (e.g., the data is successfully deleted or the delete cancelled for server-side reasons). Receives as parameters the data returned from the request and an array of the posted values of type id=value1,value2.
When used this event should return array with the following items [success, message]
where success is a boolean value if true the process continues, if false a error message appear and all other processing is stopped.
afterSubmit : function(response, postdata)
{
…
return [succes,message]
}
Regarding your second problem, I am not sure why the Ajax window will not close. Have you debugged the code to see if you are receiving a JavaScript error at that time? If not, it may be necessary for you to post a small example demonstrating the problem.

It's not good to use HTTP GET for delete operation. Do you want that the previous server response on the same URL will be cached and not send to the server? Default value of mtype is 'POST'. If you have RESTfull services on the server side you will need to use mtype: 'DELETE', but the usage of 'GET' can have sense only for the some dummy code which don't delete anything on the server.
Moreover you use dataType: 'json' parameter which is not exist for delGridRow (see the documentation). Even if you would use ajaxDelOptions: { datyType: "json" } you will get the server response (see the answer of Justin) not automatically converted from JSON to object. The reason is that the current code of delGridRow use complete callback instead of success callback (see here). So if you get JSON response from the server you will have to call $.parseJSON explicitly inside of afterSubmit callback (see the Justin's answer).

Related

when exporting to excel JqGrid,I Get error "TypeError: b.url is null "

I use jqGrid v5.3 in my asp.net MVC Project(Guriddo jqGrid JS - v5.3.0 - 2018-02-
01)
grid work in a good way ,every think is good
but when I want export grid to excel,I get this error:
TypeError: b.url is null
how can I solve that?
I using "jquery-2.1.1" and add these scripts to my projects:
<script src="~/Scripts/jqgrid/js/i18n/grid.locale-en.js"></script>
<script src="~/Scripts/jqgrid/js/jquery.jqGrid.min.js"></script>
<script src="~/Scripts/jqgrid/src/grid.export.js"></script>
and here is my JavaScript code:
$(document).ready(function () {
debugger;
LoadCustomerOrders();
});
function LoadCustomerOrders() {
// Make sure IE allows us to load JSON data from the iNorthwind website
jQuery.support.cors = true;
// Load our JSON data, and populate the jqGrid control with it
$("#tblOrders").jqGrid({
url: 'http://www.inorthwind.com/Service1.svc/getOrdersForCustomer/BERGS',
contentType: "application/json",
datatype: "json",
data: "{}",
jsonReader: {
root: "GetOrdersForCustomerResult", //arry containing actual data
id: "OrderID", //index of the column with the PK in it
repeatitems: false
},
mtype: "GET",
colNames: ["ID", "Order Date", "Name",
"Address", "City", "Postcode", "Shipped Date"],
colModel: [
{ name: "OrderID", width: 70, align: "center", search: false },
{ name: "OrderDate", search: true, width: 100 },
{ name: "ShipName", search: true, width: 120 },
{ name: "ShipAddress", search: true, hidden: true },
{ name: "ShipCity", search: true, width: 200 },
{ name: "ShipPostcode", search: true, width: 140 },
{ name: "ShippedDate", search: true, width: 80, align: "center" }
],
pager: "#pager",
width: 'auto',
height: 'auto',
rowNum: 10,
rowList: [],
loadonce: true,
sortable: true,
sortname: "OrderID",
sortorder: "desc",
viewrecords: true,
gridview: true,
autoencode: true,
ignoreCase: true, // Make the "Search" popup search case-insensitive
caption: ""
});
$('#tblOrders').jqGrid('navGrid', '#pager', {
search: true,
searchtext: "Search", // Make the Search icon have a "Search" label next to it
edit: false,
add: false,
del: false,
refresh: false
},
{}, // default settings for edit
{}, // default settings for add
{}, // delete
{
closeOnEscape: true, closeAfterSearch: true, ignoreCase: true, multipleSearch: false, multipleGroup: false, showQuery: false,
sopt: ['cn', 'eq', 'ne'],
defaultSearch: 'cn'
}).navButtonAdd('#pager', {
caption: "Export to Excel",
buttonicon: "ui-icon-disk",
onClickButton: function () {
ExportDataToExcel("#tblOrders");
},
position: "last"
});
}
function ExportDataToExcel(tableCtrl) {
// Export the data from our jqGrid into a "real" Excel 2007 file
// ExportJQGridDataToExcel(tableCtrl, "CustomerOrders.xlsx");
var gridData = $("#tblOrders").jqGrid('getRowData');
var dataToSend = JSON.stringify(gridData);
jQuery("#tblOrders").jqGrid('excelExport', dataToSend);
}
I think you use not the correct method to export the data to excel using Guriddo jqGrid. You use excelExport, which only send a parameters to the server and expect a export to be done at server. You need to use the exportToExcel method instead. Here is the documentation. Please look at this example
One more additional note - you do not need to include the grid.export.js file. This file is already included into the jquery.jqGrid.min file which you use.

jqgrid jsonReader configuration

I'm new to jqgrid finally i've setup a grid. Suppose i need to setup jsonReader so that the grid knows where to get my grid-data in the json return. However i got blank cells after trying for days.
Here is my grid:
jQuery("#list48").jqGrid({
url: 'dbtest.aspx/get_offsite_history2',
datatype: "json",
mtype: 'POST',
ajaxGridOptions: { contentType: "application/json" },
serializeGridData: function(postData) {
return JSON.stringify(postData);
},
jsonReader: {
root: function(obj) { alert(JSON.stringify(obj.d)); return obj.d; },
repeatitems: false
},
height: 'auto',
rowNum: 30,
rowList: [10, 20, 30],
colNames: ['name', 'start_date', 'duration', 'offsite_cat'],
colModel: [
{ name: 'name', index: 'name', width: 80, align: 'left', editable: true, edittype: 'text' },
{ name: 'start_date', index: 'start_date', width: 120, align: 'left', editable: true, edittype: 'text' },
{ name: 'duration', index: 'duration', width: 120, align: 'left', editable: true, edittype: 'text' },
{ name: 'offsite_cat', index: 'offsite_cat', width: 120, align: 'left', editable: true, edittype: 'text'}],
pager: "#plist48",
viewrecords: true,
sortname: 'name',
caption: "Grouping Array Data",
gridview: true
});
This is the server return from url dbtest.aspx/get_offsite_history2:
{"d":"[{\"name\":\"A\",\"start_date\":\"B\",\"duration\":\"C\",\"offsite_cat\":\"D\"}]"}
i suppose to get the result by setting "root: 'd'" but i got 64 blank rows for that...
look for comments... many thanks
The reason of your problem is the bug in your server code. You make serialization to JSON twice. After deserializing of d property of the server response you get still JSON string (!!!) instead of object. Typical error is manual usage of JavaScriptSerializer.Serialize in the web method. One should return the object itself instead of the string which is the result of serializing.
Without modifying of your current server code you can fix the problem by usage of
jsonReader: {
root: function (obj) {
alert(typeof obj.d === "string" ? obj.d : JSON.stringify(obj.d));
return typeof obj.d === "string" ? $.parseJSON(obj.d) : obj.d;
},
repeatitems: false,
page: function () { return 1; },
total: function () { return 1; },
records: function (obj) {
return typeof obj.d === "string" ? $.parseJSON(obj.d).length : obj.length;
}
}
or (if you use loadonce: true) just
jsonReader: {
root: function (obj) {
return typeof obj.d === "string" ? $.parseJSON(obj.d) : obj.d;
},
repeatitems: false
}
Because your current server code seems not implemented the paging of data you should increase rowNum to some large enough value like rowNum: 10000 or to use loadonce: true.
UPDATED: You can find here modified demo which works. It displays
after the alert message.
I think the problem is the structure of your returned json data.
Below is one that I use :
{ "page":1,
"rows":[{"id":"1","cell":["1","1","Row 1","3","9",""]},
{"id":"2","cell":["2","2","Row 2","2","1",""]},
{"id":"3","cell":["3","4","Row 3","2","0",""]}],
"records":3,
"total":1
}
You may need to add a colModel for id to uniquely identify each row.
e.g.
colNames: ['id', 'name', 'start_date', 'duration', 'offsite_cat'],
colModel: [
{ name: 'id', index: 'id', hidden: true },
{ name: 'name', index: 'name', width: 80, align: 'left', editable: true, edittype: 'text' },
{ name: 'start_date', index: 'start_date', width: 120, align: 'left', editable: true, edittype: 'text' },
{ name: 'duration', index: 'duration', width: 120, align: 'left', editable: true, edittype: 'text' },
{ name: 'offsite_cat', index: 'offsite_cat', width: 120, align: 'left', editable: true, edittype: 'text'}],
Hope that helps.

How to add DropdownMenu for JqgridFilterToolbar Column

Hii Guys!!!
I made jqgrid in which i added a FilterToolbar.Now as per my need i need dropdownmenu for unique values in FilterToolbar column.I am using asp.net...
Here is my code...
$(function () {
$("#UsersGrid").jqGrid({
url: 'jqGridHandler.ashx',
datatype: 'json',
height: 250,
colNames: ['UserID', 'UserName', 'FirstName', 'MiddleName', 'LastName', 'EmailID'],
colModel: [
{ name: 'UserID', index: 'UserID', width: 100, sortable: true },
{ name: 'UserName', width: 100, sortable: true },
{ name: 'FirstName', width: 100, sortable: true },
{ name: 'MiddleName', width: 100, sortable: true },
{ name: 'LastName', width: 100, sortable: true },
{ name: 'EmailID', width: 150, sortable: true }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: '#UsersGridPager',
sortname: 'UserID',
viewrecords: true,
sortorder: 'asc',
autowidth:true
//caption: 'JSON Example'
});
$("#UsersGrid").jqGrid('navGrid', '#UsersGridPager', { edit: false, add: false, del: false });
$("#UsersGrid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter:true, defaultSearch: 'cn' });
$("#UsersGrid").jqGrid('navButtonAdd', '#UsersGrid-pager', { caption: "Filter", title: "Toggle Searching Toolbar", buttonicon: 'ui-icon-pin-s', onClickButton: function () { $("#UsersGrid")[0].toggleToolbar(); }
});
Plz guys help me to get the solution..
Thanx in advance....
The easiest way is the usage stype: "select". If you want fill dropdown with unique value from the column you can do this either on the server side or on the client side. If you provide all possible the unique values on the server side in form HTML fragment of <select> you can specify dataUrl option of searchoptions (or editoptions). If you provide the data on the client side you can specify value property of searchoptions (or editoptions) instead. In the answer you will find the example of possible implementation.

jqGrid loading aspx webservice using mtype post json not loading grid

I have been struggling with getting this to work for a number of days now.
oddly , I have gotten it to sort of work through various trials - but now its not loading at all
here is my setup:
$("#table-Select").jqGrid({
url: 'SelectionListService.asmx/GetList',
mtype: 'POST',
datatype: 'json',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
postData: { SelectionType: 'Project' },
colNames: ['id', 'Title', 'DocumentID'],
colModel: [
{ name: 'id', index: 'id', width: 20,hidden: false },
{ name: 'Title', index: 'Title' ,width: 220,hidden:false},
{ name: 'DocumentID', index: 'DocumentID',width: 220, hidden: false}
],
hidegird: false,
autowidth: true,
//height: 'auto',
rowNum: 0,
rowList: [10, 20, 30],
pager: jQuery('#table-SelectPager'),
sortname: 'Title',
viewrecords: true,
loadonce: true,
sortorder: "desc",
caption: "Select Project",
//fixes Invalid JSON Primitive error
serializeGridData: function (postData) {
if (postData.searchField === undefined) postData.searchField = null;
if (postData.searchString === undefined) postData.searchString = null;
if (postData.searchOper === undefined) postData.searchOper = null;
//if (postData.filters === undefined) postData.filters = null;
return JSON.stringify(postData);
},
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records"
}
}).navGrid('#table-SelectPager', { edit: false, add: false, del: false });
Here is the JSON data coming from the WebService call :
{"d":{"__type":"NCR.SelectionListService+JQGrid","page":1,"total":4,"records":4,"rows":[{"id":"1","DocumentID":"pgmprj://aecomme/newdohaportproject/envcomp","Title":"NDPP-Environmental Compliance Monitoring"},{"id":"2","DocumentID":"pgmprj://aecomme/newdohaportproject/ndpp-portbasinandinnerbreakwatersconstruction","Title":"NDPP-Port Basin and Inner Breakwaters Construction"},{"id":"3","DocumentID":"pgmprj://aecomme/newdohaportproject/ndpp-programmanagement","Title":"NDPP-Program Management"},{"id":"4","DocumentID":"pgmprj://aecomme/newdohaportproject/ndpp-supplementarysiteinvestigation","Title":"NDPP-Supplementary Site Investigation"}]}}
I know it must be something simple i am missing - but after all of the examples I have looked at - I have no idea what I am missing.
Any thoughts would be greatly appreciated.
You should modify the jsonReader option to the following:
jsonReader: {
root: "d.rows",
page: "d.page",
total: "d.total",
records: "d.records",
repeatitems: false
}
See the demo.

I could not able to see Add. Edit, Delete and View using JQGrid

I have
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '/TabMaster/GetGridData',
datatype: 'json',
mtype: 'GET',
colNames: ['col ID', 'First Name', 'Last Name', '', '', '', ''],
colModel: [
{ name: 'colID', index: 'colID', width: 100, align: 'left' },
{ name: 'FirstName', index: 'FirstName', width: 150, align: 'left' },
{ name: 'LastName', index: 'LastName', width: 300, align: 'left' },
{ name: 'add', width: 18, sortable: false, search: false,
formatter: function () {
return "<span class='ui-icon ui-icon-plus'></span>"
}
},
{ name: 'edit', width: 18, sortable: false, search: false,
formatter: function () {
return "<span class='ui-icon ui-icon-pencil'></span>"
}
},
{ name: 'del', width: 18, sortable: false, search: false,
formatter: function () {
return "<span class='ui-icon ui-icon-trash'></span>"
}
},
{ name: 'details', width: 18, sortable: false, search: false,
formatter: function () {
return "<span class='ui-icon ui-icon-document'></span>"
}
}
],
onSelectRow: function (rowJsonId)
{ handleSelectedRow(rowJsonId); },
pager: jQuery('#pager'),
rowNum: 4,
rowList: [1, 2, 4, 5, 10],
sortname: 'colID',
sortorder: "asc",
viewrecords: true,
gridview: true,
rownumbers: true,
multiselect: true,
imgpath: '/scripts/themes/steel/images',
caption: 'Tab Master Information'
}).navGrid(pager, { edit: true, add: true, del: true, refresh: true, search: true });
});
function handleSelectedRow(thing) {
}
but i could not able to see buttons for Add, Edit, Delete and View i am only able to see for empty column in JQGrid.
for your reference
Please provide your valuable comments for the same.
It seems to me that you try to use my demo from the answer:
All classes for the ui-icon-plus, ui-icon-trash and so on come from jQuery UI CSS. You shoul just verify that you included jQuery UI correctly together with the images subdirectory.

Resources