How to delete selected rows from server and reload grid? - jqgrid

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');

Related

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 load json data by ajax call in jqgrid

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.

Editing on external file Jqgrid

I have some data displayed on a grid generated with JQgrid. I want to do the edit of a selected row on a separate PHP file. What I need is that when I click a row on the Jqgrid, I got an ID for the selected row, and send it as a parameter to that separate PHP file, which is called by pressing a button that is not part of the grid, also warn the user if he press the edit button and no row is selected on the JQGrid. Somebody know how to do this?
Below is the code of the JQgrid table that I'm creating for the JQGrid, with the button to redirect to the other file:
<div>
<h1>Manejo de alumnos</h1>
<table id="list"></table><!--Grid table-->
<div id="pager"></div> <!--pagination div-->
</div>
<br>
Editar alumno
Here is the code of my JQgrid:
$(document).ready(function (){
jQuery("#list").jqGrid({
url: 'http://localhost/ProyectoNetbeans/CodeIgniter_2.1.3/index.php/Alumnos_controller/loadData',
mtype : "post", //Ajax request type. It also could be GET
datatype: "json", //supported formats XML, JSON or Arrray
colNames:['Expediente','Primer apellido','Segundo apellido', 'Nombre','Cédula'], //Grid column headings
colModel:[
{name:'expediente',index:'expediente', width:300, editable:true, edittype:'text'},
{name:'primerApellido',index:'primerApellido', width:300, editable:true, edittype:'text'},
{name:'segundoApellido',index:'segundoApellido', width:300, editable:true, edittype:'text'},
{name:'nombre',index:'nombre', width:300, editable:true, edittype:'text'},
{name:'cedula',index:'cedula', width:300, editable:true, edittype:'text'}
],
pager: '#pager',
rowNum:10,
rowList:[15,30],
sortname: 'primerApellido',
reloadAfterSubmit: true,
sortorder: 'asc',
viewrecords: true,
postData: {expediente:"expediente"},
caption: 'Alumnos'
}).navGrid('#pager',{edit:false,add:false,del:true},
{//EDITAR
url:"http://localhost/ProyectoNetbeans/CodeIgniter_2.1.3/index.php/Alumnos_controller/deleteData"
},
{
//AGREGAR
},
{// DELETE
jqModal:false,
reloadAfterSubmit:true,
savekey: [true,13],
drag: true,
closeOnEscape:true,
closeAfterAdd:true,
url:"http://localhost/ProyectoNetbeans/CodeIgniter_2.1.3/index.php/Alumnos_controller/deleteData",
onclickSubmit:function(params, postdata){
var index=$("#list").getGridParam("selrow");
var rowId = jQuery('#list tr:eq('+index+')').attr('ID');
var dataFromTheRow = jQuery('#list').jqGrid ('getRowData', rowId);
var dataFromCellByColumnName = jQuery('#list').jqGrid ('getCell', rowId, 'expediente');
return { expediente: dataFromCellByColumnName };
}
},
{multipleSearch : false}, // enable the advanced searching
{closeOnEscape:true} /* allow the view dialog to be closed when user press ESC key*/
);
});
You can hook up an event every time a row is selected where you pass the information to your Edit Button via:
onSelectRow: function(id){
//pass id to button
and then you can test when the edit button is pressed if a row is selected by
if ($('#gridName').jqGrid('getGridParam', 'selrow')) {
...
}
else {
return false;
}
I was able to solve this using Mark's answer and doing some investigation. First, you need to pass some parameter which is going to be used by the button, this parameter will depend on the logic of your grid. The code to get the parameter is the following, you need to place this in the section which contain the ColModel:
onSelectRow: function(id)
{
var dataFromCellByColumnName="";
var index=$("#list").getGridParam("selrow");
var rowId = jQuery('#list tr:eq('+index+')').attr('ID');
var dataFromTheRow = jQuery('#list').jqGrid ('getRowData', rowId);
dataFromCellByColumnName = jQuery('#list').jqGrid ('getCell', rowId, 'expediente');
setExpediente(dataFromCellByColumnName);
}
On this particular case, I'm sending the "expediente" field of the grid to the "setExpediente" function. The setExpediente function is:
var expediente="";
function setExpediente(elExpediente)
{
expediente = elExpediente;
}
Note that the variable "expediente" is a global variable. Then, you need to create a function that will use the global variable "expediente". I made this one:
function revisarSeleccion()
{
if (expediente=="")
{
alert("Seleccione una fila")
}
else
{
alert(expediente);
}
}
This will check if the variable "expediente" is blank or not, and depending on the results you can make your decisions.
Thanks to Mark for his help on this.

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.

Jqgrid: navigation based on the selected row

I was trying to enable navigation based on a selected row. So, the user select a row from jQgrid, and when press the show (is there a show button for the grid, I saw edit, add etc), it needs to go to a new page based on the url (part of the row).
$(document).ready(function () {
function getLink() {
// var rowid = $("#customer_list").jqGrid('getGridParam', 'selrow');
var rowid = $("#customer_list").getGridParam('selrow');
var MyCellData = $("#customer_list").jqGrid('getCell', rowid, 'dataUrl');
return MyCellData;
}
$("#customer_list").jqGrid({
url:'mytestList',
editurl:'jq_edit_test',
datatype: "json",
colNames:['Call Id','Title','dataUrl'],
colModel:[
{name:'callId', width:80, search:false},
{name:'title', width:200, sortable:false},
{name:'dataUrl',hidden:true}
],
rowNum:10,
sortname:'lastUpdated',
sortorder: 'desc',
pager:'#customer_list_pager',
viewrecords: true,
gridview: true
}).navGrid('#customer_list_pager',
{add:true,edit:true,del:false,search:true,refresh:true},
{closeAfterEdit:true, afterSubmit:afterSubmitEvent}, // edit options
{addCaption:'Create New something', afterSubmit:afterSubmitEvent,
savekey:[true,13]}, // add options
{afterSubmit:afterSubmitEvent} // delete options
);
$("#customer_list").jqGrid('filterToolbar');
});
so, the url is passed for each row as dataUrl. I'm trying to read it and set to the button. When debug through firebug, the rowid was 223 (there were only 12 rows in the grid), and the cell value is empty. Currently the button is kept outside the grid, but it may better to be it part of the vavGrid
thanks.
The code like following could solve your problem
$("#customer_list").jqGrid ('navButtonAdd', '#customer_list_pager',
{ caption: ""/*"Show"*/, buttonicon: "ui-icon-extlink", title: "Show Link",
onClickButton: function() {
var grid = $("#customer_list");
var rowid = grid.jqGrid('getGridParam', 'selrow');
window.location = grid.jqGrid('getCell', rowid, 'dataUrl');
}
});
You could just make the show button be part of each row in the grid and use a custom formatter to turn it into a URL.
Based on the example in the wiki, you'll probably need something along the lines of
function myformatter ( cellvalue, options, rowObject )
{
return "Show";
}

Resources