JQGrid: get multiple checked row values in JQGrid by post - php

I have one JQGrid in my php file and I have placed inside one form . On submitting form, i just want the checked value from the JQGrid.
<script type="text/javascript">
$(function() {
$("#list1").jqGrid({
url:'revMemberJson.php',
datatype: 'json',
mtype: 'GET',
loadonce: true,
// jsonReader: { repeatitems: false },
colNames:['Name','Mobile'],
colModel :[
{name:'name', index:'name',width: 100,searchoptions: { sopt: ['eq', 'ne','cn']}},
{name:'mobile', index:'mobile',search: false,width: 120}
],
pager: '#pager',
rowNum: 5,
rowList:[5,20,30],
rownumbers: true,
multiselect:true,
sortname: 'id',
sortorder: 'desc',
viewrecords: true,
height: 'auto',
width: 420,
shrinkToFit: false,
gridview: true,
caption: 'Members'
});
jQuery("#list1").jqGrid('navGrid','#pager',{edit:false,add:false,del:false});
});
var myGrid = $('#list1'),
selRowId = myGrid.jqGrid ('getGridParam', 'selrow'),
celValue = myGrid.jqGrid ('getCell', selRowId, 'mobile');
</script>
And I have used the following code to get the checked value , But All stuff are made in java script. But I have to get the values for updating the database. So i need to get the value by post.
Please provide me the methods..

You should use
var selRowIds = myGrid.jqGrid ('getGridParam', 'selarrrow');
insteda of
var selRowId = myGrid.jqGrid ('getGridParam', 'selrow');
to get the array with ids of selected rows. You can use JSON.stringify(selRowIds) or selRowIds.join(',') to convert array in the form which you can easy send to the server.
I think that you can find some additional information in the answer (see the demo).

Related

jqgrid using local data only displays one row

I'm having trouble with a search results page. The search page has 16 inputs and the results page uses a dynamic query to fetch the results and input them into an array which is used (with json_encode) to populate a jqgrid with the results. However, the grid is only displaying the first record. I've added a php "echo
json_encode()..." script to the page to view the json formatted results and it's showing all the records in the search results, so I don't know why the grid is only displaying the first row. I'd appreciate any help I can get on this. Here is the script for the grid (I'm not including the dynamic query or the array scripts because they're working fine):
$(document).ready(function () {
$("#slist").jqGrid({
data: "srchres",
datatype: "local",
mtype: "GET",
colNames: ['ProjectID', 'Customer Name', 'Invoice Number', 'Vehicle Info.', 'Project Date'],
colModel: [
{name:'ProjectID', index:'ProjectID', align:'right', hidden:true, editable:false},
{name:'CustomerName', index:'CustomerName', editable:false, width:175, align:'center'},
{name:'InvoiceNumber', index:'InvoiceNumber', editable:false, width:175, align:'center'},
{name:'VehicleInfo', index:'VehicleInfo', width:350, align:'left', editable:false},
{name:'ProjectDate', index:'ProjectDate', editable:false, width:125, align:'center', formatter: 'date', formatoptions: { newformat: 'm/d/Y' }},
],
jsonReader: {repeatitems: false, id: "ProjectID"},
onSelectRow: function (rowid) {
var rowData = $(this).getRowData(rowid);
document.location.href = "../manageproject.php?pid=" + rowData['ProjectID'];
},
pager: "#spager",
loadonce: true,
rowNum: 20,
rowList: [],
width: "auto",
height: "auto",
caption: "",
sortname: "",
sortorder: "",
viewrecords: true,
gridview: true
});
var srchres = <?php echo json_encode($projects_array); ?>;
for(var i=0;i<srchres.length;i++)
jQuery("#slist").addRowData(srchres[i].id,srchres[i]);
});
Try with the following settings into the grid:
$(document).ready(function () {
var srchres = <?php echo json_encode($projects_array); ?>;
$("#slist").jqGrid({
data: srchres,
datatype: "local",
....
});
...
});
Note the variable srchres and how is defined into the grid options. addRowData is not needed to be used.

Jqgrid don't show data

I'm using jqgrid to show data from a database, I have this HTML file:
<script type="text/javascript">
jQuery().ready(function (){jQuery("#tblclientes").jqGrid({
url: "category.php",
datatype: "xml",
mtype: "GET",
colNames: ["ID", "Categorias Es", "Categorias En", "Categorias Ru"],
colModel: [
{ name: "idCategoria", width: 55 },
{ name: "nomCategoriaEs", width: 200 },
{ name: "nomCategoriaEn", width: 200, align: "right" },
{ name: "nomCategoriaRu", width: 200, align: "right" },
],
pager: jQuery("#paginacion"),
rowNum:10,
rowList:[10,20,30],
sortname: "idCategoria",
sortorder: "desc",
viewrecords: true,
gridview: true,
autoencode: true,
caption:"XML Example" }).navGrid('#paginacion',{edit:false,add:false,del:false});
});
</script>
And this is my XML file created by the PHP file:
<?xml version='1.0' encoding='utf-8'?><rows><page>1</page><total>2</total><records>13</records><row id="1"><cell>1</cell><cell>Coke Drums</cell><cell>Coke Drums</cell><cell>Коксовые камеры</cell></row><row id="2"><cell>2</cell><cell>Columnas</cell><cell>Columns</cell><cell>Колонны</cell></row><row id="3"><cell>3</cell><cell>Reactores</cell><cell>Reactors</cell><cell>Реакторы</cell></row><row id="4"><cell>4</cell><cell>Intercambiadores de Calor</cell><cell>Heat Exchangers</cell><cell>Теплообменное оборудование</cell></row><row id="5"><cell>5</cell><cell>Autoclaves</cell><cell>Autoclaves</cell><cell>Автоклавы</cell></row><row id="6"><cell>6</cell><cell>Separadores</cell><cell>Separators</cell><cell>Сепараторы</cell></row><row id="7"><cell>7</cell><cell>Drums</cell><cell>Drums</cell><cell>Баки для нефтепродуктов</cell></row><row id="8"><cell>8</cell><cell>Módulos / Skid</cell><cell>Process Modules / Skid</cell><cell>Технологические модули, модульные основания</cell></row><row id="9"><cell>9</cell><cell>Tanques</cell><cell>Storage Tanks</cell><cell>Резервуары для хранения нефтепродуктов</cell></row><row id="10"><cell>10</cell><cell>Fundaciones OWF</cell><cell>OWF Fundations</cell><cell>Фундаменты для ветровых энергоустановок</cell></row></rows>
The Jqgrid appears as I want, but without data.
I don't see any important errors in the code or in the data which you posted. The demo uses the same code (with minimal modifications) and the same data saved as file and all works. I would recommend you to use loadError callback (see the answer) to see more information which kind of error you have.

How does editData work?

JqGrid documentation states the following regarding postData:
an array used to add content to the data posted to the server
And that's it. So, I'm using postData to send a variable to my PHP so that I can use a switch case to call the function I want.
This allows me to have a single PHP page containing all the functions for my project. I want to do the same thing with editData so I don't need a PHP page for every inline editing function associated with the project.
However, editData doesn't seem to be passing to the PHP page. I tried printing the POSTed variables to a file and they were empty. Suggestions?
Note: I am aware of the editData bug, but this should have been fixed by version 4.4.4 which is the one I'm using
$("#list").jqGrid({
url:'functions.php',
datatype:'xml',
mtype:'POST',
postData: {
action:'popGrid',
sqlCount:sqlCount,
sqlSelect:sqlSelect,
sqlSelect2:sqlSelect2,
label1:label1,
label2:label2,
},
colNames:['Label','Account_Num','Amount', 'Type Code', 'Record Code', 'Sequence'],
colModel :[
{name:'label', index:'label', width:150, align:'center', sortable:false, editable:true},
{name:'cntrct_id', index:'cntrct_id', width:150, align:'center', sortable:true},
{name:'amount', index:'amount', width:150, align:'center', sortable:false, editable:true},
{name:'type_cd', index:'type_cd', width:150, align:'center', sortable:false, editable:true},
{name:'rec_cd', index:'rec_cd', width:150, align:'center', sortable:false},
{name:'db_seq', index:'db_seq', width:150, align:'center', sortable:false},
],
editurl: 'functions.php',
extraparam: { action: function(){ return 'grdAdjust'; } },
onSelectRow: function(id) {
if(id && id!==lastSel) {
jQuery('#list').restoreRow(lastSel);
jQuery('#list').editRow(id,true);
lastSel=id;
}
},
pager: '#pager',
rowNum:100,
rowList:[100,200,300,400,500,600,700,800,900,1000],
sortname: 'cntrct_id',
sortorder: 'desc',
viewrecords: true,
caption: 'Adjustments'
});
The option editData play the same role in form editing as postData in the main grid. On the other side you wrote about "inline editing" in the text of your question. In the case you should use extraparam option instead (see the documentation). If you need to have common options of inline editing then probably the usage defalut settings in $.jgrid.inlineEdit could be helpful for you. You don't posted any code and I am not sure which editing mode and in which way you use, so I can't include more examples of usage editData, extraparam etc.
UPDATED: You use extraparam in a wrong way now. extraparam is not jqGrid option, it's option of editRow. Correct usage could be about the following:
onSelectRow: function (id) {
if (id && id !== lastSel){
$(this).jqGrid("restoreRow", lastSel);
$(this).jqGrid("editRow", id, {
keys: true,
extraparam: {
action: function () {
return 'grdAdjust';
}
}
});
lastSel = id;
}
}
If you need post constant value of action you can use simplified form of extraparam: like extraparam: {action: 'grdAdjust'}. The usage of functions is really helpful if you need return the value of some variable or some element from the page which will be changed between different calls of editRow.
Additionally I would recommend you to include gridview: true option of jqGrid and to simplify colModel which you use. If index has the same value as name you can emit it. The default value of width is already 150, so you don't need specify width:150 too. If you want use align:'center' in all or in the most columns you can change the default value of align for the grid by including cmTemplate: {align:'center'} option in the grid. Because the most column has sortable: false you can include the setting in the cmTemplate too. As the result you can reduce colModel to the following:
colModel: [
{name: 'label', editable: true},
{name: 'cntrct_id', sortable: true},
{name: 'amount', editable: true},
{name: 'type_cd', editable: true},
{name: 'rec_cd'},
{name: 'db_seq'},
],
cmTemplate: {align: 'center', sortable: false},
Such changes simplify the code not only for reading, but for maintain too. See here more information about column templates.

JQGrid: Results are blank when performing a new search

I currently have a JQGrid implementation. The first time I run the search it populates the grid just fine. When I click the search again, even if I use the same criteria the grid refreshes blank instead of using the returned data. Does anyone have any thoughts as to why this would be?
Here is my searchfunction:
function searchlibrary(searchInfo){
if(searchInfo == undefined){
searchInfo = null;
}
$("#searchlist").jqGrid({
url:'./searchlibrary',
datatype: 'json',
mtype: 'POST',
postData: searchInfo,
colNames:['Resource Name','Unit', 'Topic','Document Type','Content Type','Select'],
colModel :[
{name:'resourceName', index:'resourceName', width:374, align:'left'},
{name:'unit', index:'unitID', width:40, align:'center',sortable:true,sorttype:'text'},
{name:'topic', index:'topicID', width:220, align:'center',sortable:true},
{name:'docType', index:'docTypeID', width:97, align:'center',sortable:true},
{name:'contentType', index:'contentTypeID', width:97, align:'center',sortable:true},
{name: 'resourceID', width:55, align: "center", sortable: false, editable: true, edittype: "checkbox", editoptions: {value: "Yes:No"}}
],
rowNum:20,
sortname: 'resourceName',
sortorder: 'asc',
viewrecords: true,
gridview: true,
width:878,
height:251
});
$("#searchlist").jqGrid('setLabel','resourceName','',{'text-align':'left','padding-left':'5px'});
}
There is a dropwdown of items above the grid. When one item is selected either another dropdown with more content shows, or a textbox shows. Then when the user clicks the submit button the contents of the dropdowns/textfield are taken by jquery and an object is built. That object is passed as the searchInfo argument when the searchlibrary function is called. That is then used as the postData in the jqgrid call. I've logged to make sure the object that's being passed is always correct. For some reason anything after the first call to this function returns a blank jqgrid. Also, just for further understand the url called to retrieve the info is a php file that generates json data.
UPDATE
Here's my attempt at Oleg's suggestion. I must be missing something. I'm getting blanks again. Here's the code I'm using now.
$(document).ready(function(){
$("#searchlist").jqGrid({
url:'./searchlibrary',
datatype: 'json',
mtype: 'POST',
postData: {data: function(){var myvar = new Object(); myvar = getSearchData(); console.log(myvar); return myvar;}},
colNames:['Resource Name','Unit', 'Topic','Document Type','Content Type','Select'],
colModel :[
{name:'resourceName', index:'resourceName', width:380, align:'left'},
{name:'unit', index:'unitID', width:40, align:'center',sortable:true,sorttype:'text'},
{name:'topic', index:'topicID', width:220, align:'center',sortable:true},
{name:'docType', index:'docTypeID', width:97, align:'center',sortable:true},
{name:'contentType', index:'contentTypeID', width:97, align:'center',sortable:true},
{name: 'select', width:55, align: "center", sortable: false, editable: true, edittype: "checkbox", formatter:"checkbox", editoptions: {value: "Yes:No"},formatoptions: {disabled : false}}
],
rowNum:20,
sortname: 'resourceName',
sortorder: 'asc',
viewrecords: true,
gridview: true,
width:878,
height:251
});
$("#searchlist").jqGrid('setLabel','resourceName','',{'text-align':'left'});
function getSearchData(){
var searchType = $('select[name="searchtype"]').val();
var searchCriteria = "";
var searchInfo = new Object();
if(searchType=="Unit" || searchType=="Topic" || searchType=="Document Type"){
searchCriteria = $('select[name="searchcontent_select"]').val();
} else if(searchType=="Resource Name" || searchType=="Keyword"){
searchCriteria = $('input[name="searchcontent_text"]').val();
}
searchInfo = {type:searchType, criteria:searchCriteria}
return searchInfo;
}
$('#searchbutton').click(function(ev){
$("#searchlist").trigger('reloadGrid');
});
});
WORKING SOLUTION
$(document).ready(function(){
$("#searchlist").jqGrid({
url:'./searchlibrary',
datatype: 'json',
mtype: 'POST',
postData: {type: function(){return $('select[name="searchtype"]').val();},
criteria: function(){return getSearchData();}
},
colNames:['Resource Name','Unit', 'Topic','Document Type','Content Type','Select'],
colModel :[
{name:'resourceName', index:'resourceName', width:380, align:'left'},
{name:'unit', index:'unitID', width:40, align:'center',sortable:true,sorttype:'text'},
{name:'topic', index:'topicID', width:220, align:'center',sortable:true},
{name:'docType', index:'docTypeID', width:97, align:'center',sortable:true},
{name:'contentType', index:'contentTypeID', width:97, align:'center',sortable:true},
{name: 'select', width:55, align: "center", sortable: false, editable: true, edittype: "checkbox", formatter:"checkbox", editoptions: {value: "Yes:No"},formatoptions: {disabled : false}}
],
rowNum:20,
sortname: 'resourceName',
sortorder: 'asc',
viewrecords: true,
gridview: true,
width:878,
height:251
});
$("#searchlist").jqGrid('setLabel','resourceName','',{'text-align':'left'});
function getSearchData(){
var searchType = $('select[name="searchtype"]').val();
var searchCriteria = "";
var searchInfo;
if(searchType=="Unit" || searchType=="Topic" || searchType=="Document Type"){
searchCriteria = $('select[name="searchcontent_select"]').val();
} else if(searchType=="Resource Name" || searchType=="Keyword"){
searchCriteria = $('input[name="searchcontent_text"]').val();
}
searchInfo = {type:searchType, criteria:searchCriteria}
return searchCriteria;
}
$('#searchbutton').click(function(ev){
$("#searchlist").trigger('reloadGrid');
});
});
It turns out the solution was to unload the grid first. So I added this line:
$("#searchlist").jqGrid('GridUnload');
I put in the the searchlibrary function right above the
$("#searchlist").jqGrid({
That causes the grid to completely unload the get reloaded with the proper content.
As a note I found the idea for the solution here.
The usage of $("#searchlist").trigger("reloadGrid") is more effective as the usage of $("#searchlist").jqGrid('GridUnload'). It's understand that $("#searchlist").jqGrid({...]); creates column headers, and many other grid elements. So you should create the grid once with respect of $("#searchlist").jqGrid({...]); and later use only $("#searchlist").trigger("reloadGrid").
I would recommend you to use postData with functions as properties (see here). For example
postData: {
type: function () {
return $('select[name="searchtype"]').val(); // get some data
},
criteria: function () {
return getSearchData();}
}
}
Every time if the user click on '#searchbutton' button or do sorting or paging of data the type and criteria methods will be called. So you can return current values for the proerties and send the data to the server which the user fill in some controls on the page.

Custom Search Form in JqGrid

I'm trying my hands on JqGrid with PHP MVC structure.
I do not want to use Search functionality of Jq Grid, rather I want General Keyword Search.
I'm having data in json array. Please let me know how I can perform search with my json data set.
This search should be perform on multiple columns.
This is my search form
<form name="frmsearch" id="frmsearch">
<input type="text" id="txtsearch" name="txtsearch"/>
Search
</form>
and this is my Grid
$(document).ready(function () {
jQuery("#agentlist").jqGrid({
url: "manageagents/getagents/",
datatype: "json",
mtype:"POST",
jsonReader: {
root: "rows",
page: "currpage",
total: "totalpages",
records: "totalrecords",
id: "0",
cell:"",
repeatitems: false
},
colNames: ['Id','Agent Name', 'Email Address', 'Phone No.1', 'Phone No.2','City', 'State', 'Country'],
colModel: [
... ... ...
],
rowNum:<?php echo $this->config->item('per_page');?>,
rowList:<?php echo $this->config->item('nav_page');?>,
pager: '#plist',
autowidth: true,
height: "100%",
loadonce: true,
viewrecords: true,
altRows:true,
caption: "",
}).navGrid('#plist', { edit: false, add: false, del: false, search: true, refresh: false }); ;
});
The most easy way to do what you want is to send the current value from the searching input field #txtsearch to the URL "manageagents/getagents/". It's enough to add postData parameter with the property like the name of the parameter (like myFilter) which will be sent to the server:
postData: {
myFilter: function () { return $("#txtsearch").val(); }
}
You can read more details in the answer.
Inside of doSearch function you can just call
jQuery("#agentlist").trigger("reloadGrid", [{page: 1}]);

Categories