jqgrid using local data only displays one row - php

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.

Related

jquery combine two mysql values

I use jquery (JQwidgets)to display values in a grid. I have a database with multiple columns and lets say i have in column A the value "http://www.google.com" and in column B the value "Google".
What i want is to display "Google" in the grid and when people click on it it opens the url.
Right now i have this code wich gets the variables from the database.
var source =
{
datatype: "json",
datafields: [
{ name: 'sitename', type: 'string'},
{ name: 'url', type: 'string'},
],
url: 'http://www.site.com/data.php',
cache: false
};
After that the values are displayed using this...
$("#jqxgrid").jqxGrid(
{
pagesize : 25,
pagesizeoptions: ['25', '50', '100'],
width : 1170,
theme:"black",
source: dataAdapter,
pageable: true,
autoheight: true,
selectionmode: 'multiplecellsextended',
columns: [
{ text: 'Website', datafield: 'website' , width: 700, cellsrenderer: linkrenderer},
]
});
So what i cannot get to work is to combine the two values. What i tried is this...
var website = function (row, datafield, value) {
return 'sitename' + 'url';
}
You haven't set a linkrenderer function.
Above it, add
var linkrenderer = function(row, column, value, defaultHtml, columnSettings, rowData) {
return '<a href="' + rowData.url + '">' + value + '</div>';
}
The last column rowData is a JSON object of everything already rendered, so maybe add the columns
columns: [{text: 'URL', datafield: 'url' , width: 100}, {text: 'Website', datafield: 'sitename' , width: 700, cellsrenderer: linkrenderer}]
Hiding the URL column
$("#jqxgrid").jqxGrid('hidecolumn', 'url');

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.

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.

JQGrid: get multiple checked row values in JQGrid by post

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).

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