I am building a small application. I have a PHP code which inside has a creation of jqGrid and also I have a servlet which sends a string of an array with JSONs inside.
The string looks like this:
[
{"id":1,"firstName":"Amishay","lastName":"Vaturi"},
{"id":2,"firstName":"Amir","lastName":"Bilu"},
{"id":3,"firstName":"Michael","lastName":"Keidar"},
{"id":4,"firstName":"Mika","lastName":"Spivak"},
{"id":5,"firstName":"Ksenia","lastName":"Mosorov"},
{"id":6,"firstName":"Rose","lastName":"Wahlem"}
]
The problem is I don't see it in the grid I made...
the grid code is this :
$("#jqGrid").jqGrid({
url: 'http://10.0.0.4:8080/api/students/all',
mtype: "GET",
datatype: "jsonstring",
colModel: [
{ label: 'ID', name: 'id', key: true, width: 75 , height: 50 },
{ label: 'First Name', name: 'firstName', width: 150 , height: 50},
{ label: 'Last Name', name: 'lastName', width: 150 , height: 50}
],
viewrecords: true,
width: 780,
height: 250,
rowNum: 20,
pager: "#jqGridPager"
});
I looked here and in the entire net to search for an answer.
I saw I might need to send a different json from the server. perhaps with more info such as records,number of page etc. I also saw I might need to declare a json reader in the jqGrid properties.
I did both.. still didn't work. It's like I didn't find a solution which meets my problem in a 100%.
I will be very happy to get an answer which works (:
Thanks a lot!
The error in your code is the usage of datatype: "jsonstring" instead of
datatype: "json"
By the way you don't need to create hidden column id, because jqGrid assign the value of id property to id attribute of rows (<tr> elements). Additionally I would recommend you to use loadonce: true option, because the format of data which you use don't means server side paging.
I create the demo https://jsfiddle.net/OlegKi/oc7uuh9q/, which used your data to demonstrate that all should work. I just modified your code a little to use new features implemented in free jqGrid, the fork of jqGrid, which I develop.
I have a page containing a ExtJS 4.2.2 dataStore and gridPanel showing items created using information from various tables in a MySQL database.
The purpose of the generated grid is to provide a "confirmation" to the user before any information is actually generated in the database in a table separate to those that originated the initial information, as some items can be flagged to be imported; unflagged items are not imported. The page uses HTML, PHP (with CodeIgniter MVC framework) and ExtJS (which implies Javascript and JQuery).
With my current understanding of ExtJS, I would perform the necessary database insert or update by:
Saving all the changes in the grid to the store
Packaging the store's data into a multidimensional array, which is then assigned into a POST variable in some similar manner to a form
Perform a POST to the same page, picking up the POST variable
Loop through the POST information, passing each row's data to the model to perform the SQL query and INSERT/UPDATE as necessary.
I'm thinking this is a long-winded and most likely inefficient method for doing this; having previously worked with Kendo UI, I would have thought there is some form of "save" action on the store that simply calls a controller/model function that would act on the data in fewer steps.
Having looked at Ext.data.Store's numerous potential candidates (the commitChanges method, update event, the write event, store.sync etc.), I have to say I'm completely bewildered by how I could perform the kind of action I'm thinking of; I need to write the information to a table separate from those that generated the initial information, and none of the above seem to do that.
I would appreciate a "simple words" play-by-play of how to get the "dirty" data from the grid saved to the store, then the store data being passed to a MVC Controller-then-Model function that allows for update/insert to the DB (if that is the best way to do this) - I also appreciate that I will have to modify aspects of my ExtJS code, but what about my current setup isn't helping, if anything?
ExtJS code below renders the grid with data, and not much else:
Ext.Loader.setConfig({
enabled: true
});
Ext.Loader.setPath('Ext.ux', '../ux');
Ext.require([
'Ext.ux.CheckColumn'
]);
Ext.onReady(function(){
Ext.define('ConfirmationModel', {
extend: 'Ext.data.Model',
fields: [
'GroupName', // generated if not a member of a group, will eventually be retrieved if already existing in group by checking import table for JobNo, ItemNo and ItemTypeId
'ItemType',
'ItemTypeId',
'JobNo',
'ItemNo',
'ThicknessDepth',
'Cutter',
'CutterId',
'Source',
'Qty',
'Material',
'MaterialId',
'Type',
'TypeId',
'Work',
'WorkId',
'PaintInternal',
'PaintExternal',
'Notes',
'Documented',
'ImportDate', // fetched by checking import table for jobNo, itemNo and itemTypeId
'ImportCheck' // usually automatically checked if not yet imported
]
});
confirmationStore = Ext.create('Ext.data.Store',{
model: 'ConfirmationModel',
autoLoad: true,
proxy: {
// load using HTTP
type: 'ajax',
url: '<?= $site_url ?>Production/ConfirmationJSON/<?php echo $job_no ?>', // currently pulls all the information from three separate tables, pushes to object arrays then converts to and returns as JSON; will also check import table for existing entries as further work
pageParam: false, //to remove param "page"
startParam: false, //to remove param "start"
limitParam: false, //to remove param "limit"
noCache: false, //to remove param "_dc"
reader: {
type: 'json',
model: 'ConfirmationModel'
}
},
groupField: 'GroupName'
});
confirmationGrid = Ext.create('Ext.grid.Panel', {
width: 1200,
store: confirmationStore,
title: 'Import Confirmation',
tbar: [
{
xtype: 'button',
text: 'Update',
handler: function(){
// function to handle the save/update of information goes here?
document.location.href = '<?php echo site_url() ?>Production/Schedule'; // redirect to next page in steps
}
},
{
xtype: 'button',
text: 'Cancel',
handler: function(){
window.history.back();
}
}
],
columns: [
{ text: 'Item<br />No.', width:50, dataIndex: 'ItemNo' },
{ text: 'Job<br />No.', width: 65, dataIndex: 'JobNo' },
{ text: 'Item Type', width: 70, dataIndex: 'ItemType' },
{ text: 'Thickness<br />Depth', width: 65, dataIndex: 'ThicknessDepth' },
{ text: 'Cutter', width: 65, dataIndex: 'Cutter' },
{ text: 'Source', width: 65, dataIndex: 'Source' },
{ text: 'Qty', width: 40, dataIndex: 'Qty' },
{ text: 'Material', flex: 1, dataIndex: 'Material' },
{ text: 'Type', flex: 2, dataIndex: 'Type' },
{ text: 'Work', flex: 2, dataIndex: 'Work' },
{ text: 'Paint - Internal', flex: 2, dataIndex: 'PaintInternal' },
{ text: 'Paint - External', flex: 2, dataIndex: 'PaintExternal' },
{ text: 'Notes', flex: 2, dataIndex: 'Notes' },
{ text: 'Documented?', width: 75, dataIndex: 'Documented' },
{ text: 'Import<br />Date', width: 60, dataIndex: 'ImportDate' },
{
xtype: 'checkcolumn',
sortable: false,
header: 'Import?',
width: 50,
dataIndex:'ImportCheck'
}
],
features: [{
id: 'group',
ftype: 'groupingsummary',
groupHeaderTpl: '{name}',
enableGroupingMenu: false
}],
renderTo: Ext.get('sencha_confirmation')
});
});
There's no need to save data from the grid to the store, since the content you're seeing in the grid is there because it is already in the store (given that the store is the data provider for the grid).
To send the data in this format, you simply need to configure your proxy's writer's allowSingle: false. This will force the proxy to send through the records it is persisting as an array always, even if there is only one record.
Example:
proxy: {
writer: {
allowSingle: false
},
...
}
This can be accomplished by calling sync() on your store. Sync will automatically create a request to the url specified on your proxy, and will batch together new records, updated records, and deleted records. You can call this manually, or add autoSync: true to your store (I prefer controlling when it's called, but that's up to you).
Re: the MVC side of things, that's dependent on how your application is structured. For example, if you have a "save" button on the grid, you could bind to the button's click event, and in your controller listen for this click event and call your store's sync() method there. Of course, this is just an example: there are an number of events/conditions you could respond to and do the same thing.
Hello StackOverFlow nation . I'm trying to add information to jqGrid , which is retrieved from MySQL database. I've two files => index.html and data.php (both in the same directory)
index.html source =>
<script type="text/javascript">
$(function(){
$("#jqGrid_tb").jqGrid({
url: "data.php",
datatype: "json",
sortable: true,
height: "auto",
colNames: ["Name","Surname","Birth Year","Famous Film"],
colModel: [
{name: "name", index: "name", width: "150"},
{name: "surname", index: "surname", width: "150"},
{name: "b_year", index: "year", width: "150"},
{name: "film", index: "film", width: "200"}
],
rowNum: 5,
rowList: [5,10,15],
viewrecords: true,
pager: $("#pager"),
caption: "Famous Actors",
}).navGrid("#pager");
});
</script>
<div id="grid">
<table id="jqGrid_tb"></table>
<div id="pager"></div>
</div>
data.php source =>
include ("JSON.php");
$json = new Services_JSON();
$con = new mysqli("host","user","pswd","db");
if (!$con->connect_errno){
if ($r = $con->query("SELECT * FROM actors")){
while ($row = $r->fetch_assoc()){
$info[] = array(
"name" => $row[name],
"surname" => $row[surname],
"b_year" => $row[b_year],
"film" => $row[film],
);
}
$r->free();
}
}
echo $json->encode($info);
if (isset($con)){
$con->close();
}
jqGrid is shown without any information in index.html file , also when opening data.php file information is successfully encoded into JSON format , whats wrong I can't understand . Please help , thanks ...
Your response format is wrong. You can go to jqGrid Demos page where you will find a sample for PHP/MySQL after expanding Loading Data and then choosing JSON Data.
The proper format of data should look like this:
{
"total": "1",
"page": "1",
"records": "2",
"rows": [
{ "name": "Robert", "surname": "De Niro", "b_year": "1943", "film": "Once Upon A Time In America" },
{ "name": "Al", "surname": "Pacino", "b_year":"1971", "film": "Scent Of A Woman"}
]
}
Where:
total --> total count of pages
page --> current page number
records --> total count of records
rows --> the rows of data
Also if you want rows to be objects, you need to disable repeatitems in jqGrid jsonReader options:
$("#jqGrid_tb").jqGrid({
...
jsonReader: { repeatitems: false }
});
It is also adviced for rows to have unique id for later reference.
You should include
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
}
as additional option of jqGrid is you don't want to change format of input data. Moreover you should specify which values should assign jqGrid as id attribute of the row. You can include additional id property as additional property of every returned item or you can add key: true property to the column (in colModel) which contains unique values. For example if you can guarantied that the values from "name" are already unique then you can include key: true property in definition of "name" column.
Additionally you can consider to use loadonce: true option of jqGrid. In the case the full data of the grid will be loaded at once and the sorting, paging and searching (filtering) of data will be implemented by jqGrid on the client side without needs to implement some additional code on the server side. You should don't use the option in case of large number of rows (many hundred or many thousand rows) in the grid.
I'm trying to create a jqgrid, but the table is empty. The table renders, but the data doesn't show.
The data I'm getting back from the php call is:
{
"page":"1",
"total":1,
"records":"10",
"rows":[
{"id":"2:1","cell":["1","image","Chief Scout","Highest Award test","0"]},
{"id":"2:2","cell":["2","image","Link Badge","When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)","0"]},
{"id":"2:3","cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]},
{"id":"2:4","cell":["4","image","Voyageur Scout Award","Voyageur Scout Award is the right after Pioneer Scout.","0"]},
{"id":"2:5","cell":["5","image","Voyageur Citizenship","Learning about and caring for your community.","0"]},
{"id":"2:6","cell":["6","image","Fish and Wildlife","Demonstrate your knowledge and involvement in fish and wildlife management.","0"]},
{"id":"2:7","cell":["7","image","Photography","To recognize photography knowledge and skills","0"]},
{"id":"2:8","cell":["8","image","Recycling","Demonstrate your knowledge and involvement in Recycling","0"]},
{"id":"2:10","cell":["10","image","Voyageur Leadership ","Show leadership ability","0"]},
{"id":"2:11","cell":["11","image","World Conservation","World Conservation Badge","0"]}
]}
The javascript configuration looks like so:
$("#"+tableId).jqGrid ({
url:'getAwards.php?id='+classId,
dataType : 'json',
mtype:'POST',
colNames:['Id','Badge','Name','Description',''],
colModel : [
{name:'awardId', width:30, sortable:true, align:'center'},
{name:'badge', width:40, sortable:false, align:'center'},
{name:'name', width:180, sortable:true, align:'left'},
{name:'description', width:380, sortable:true, align:'left'},
{name:'selected', width:0, sortable:false, align:'center'}
],
sortname: "awardId",
sortorder: "asc",
pager: $('#'+tableId+'_pager'),
rowNum:15,
rowList:[15,30,50],
caption: 'Awards',
viewrecords:true,
imgpath: 'scripts/jqGrid/themes/green/images',
jsonReader : {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: true,
cell: "cell",
id: "id",
userdata: "userdata",
subgrid: {root:"rows", repeatitems: true, cell:"cell" }
},
width: 700,
height: 200
});
The HTML looks like:
<table class="awardsList" id="awardsList2" class="scroll" name="awardsList" />
<div id="awardsList2_pager" class="scroll"></div>
I'm not sure that I needed to define jsonReader, since I've tried to keep to the default. If the php code will help, I can post it too.
I got it to work!
The dataType field should be datatype. It's case sensitive.
The problem also occures when you include script jquery.jqGrid.min.js before then grid.locale-en.js. Check this if there are any problems with controller's method call.
I experienced the same problem when migrating from jqGrid 3.6 to jqGrid 3.7.2. The problem was my JSON was not properly double-quoted (as required by JSON spec). jqGrid 3.6 tolerated my invalid JSON but jqGrid 3.7 is stricter.
Refer here: http://simonwillison.net/2006/Oct/11/json/
Invalid:
{
page:"1",
total:1,
records:"10",
rows:[
{"id":"2:1","cell":["1","image","Chief Scout","Highest Award test","0"]},
{"id":"2:2","cell":["2","image","Link Badge","When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)","0"]},
{"id":"2:3","cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]}
]}
Valid:
{
"page":"1",
"total":1,
"records":"10",
"rows":[
{"id":"2:1","cell":["1","image","Chief Scout","Highest Award test","0"]},
{"id":"2:2","cell":["2","image","Link Badge","When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)","0"]},
{"id":"2:3","cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]}
]}
I also got it to work: datatype is the correct spelling -- it's shown that way in the example but it is inconsistent with everything else in the library so it was easy to get wrong
I'm getting very tired chasing this sparse documentation around and I really feel like JSON, which is right and proper to be using in JavaScript, has really been given short coverage in favor of XML. Python and JavaScript together, through JSON, is a really strong combination, but it's a constant struggle with this particular library.
Anyone with an alternative that:
1> Properly supports jQuery UI themes (including rounded corners!) (http://datatables.net has much nicer support for themes)
2> Allows resizing of columns (http://datatables.net doesn't support this out of the box)
3> Allows sub-grids (http://datatables.net lets you do whatever you want here, through an event)
please let me know. I'm spending more time on this one part of my interface than on the whole rest of it combined and it's all the time spent searching for working examples and "trying things" which is just getting annoying.
S
This might be a older post but I will post my success just to help others.
Your JSON needs to be in this format:
{
"rows": [
{
"id": 1,
"cell": [
1,
"lname",
"fname",
"mi",
phone,
"cell1",
"cell2",
"address",
"email"
]
},
{
"id": 2,
"cell": [
2,
"lname",
"fname",
"mi",
phone,
"cell1",
"cell2",
"address",
"email"
]
}
]
}
and I wrote this model in Zend so you can use it if you feel like it. Manipulate it how you want.
public function fetchall ($sid, $sord)
{
$select = $this->getDbTable()->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
$select->setIntegrityCheck(false)
->join('Subdiv', 'Subdiv.SID = Contacts.SID', array("RepLastName" => "LastName",
"Subdivision" => "Subdivision",
"RepFirstName" => "FirstName"))
->order($sid . " ". $sord);
$resultset = $this->getDbTable()->fetchAll($select);
$i=0;
foreach ($resultset as $row) {
$entry = new Application_Model_Contacts();
$entry->setId($row->id);
$entry->setLastName($row->LastName);
$entry->setFirstName1($row->FirstName1);
$entry->setFirstName2($row->FirstName2);
$entry->setHomePhone($row->HomePhone);
$entry->setCell1($row->Cell1);
$entry->setCell2($row->Cell2);
$entry->setAddress($row->Address);
$entry->setSubdivision($row->Subdivision);
$entry->setRepName($row->RepFirstName . " " . $row->RepLastName);
$entry->setEmail1($row->Email1);
$entry->setEmail2($row->Email2);
$response['rows'][$i]['id'] = $entry->getId(); //id
$response['rows'][$i]['cell'] = array (
$entry->getId(),
$entry->getLastName(),
$entry->getFirstName1(),
$entry->getFirstName2(),
$entry->getHomePhone(),
$entry->getCell1(),
$entry->getCell2(),
$entry->getAddress(),
$entry->getSubdivision(),
$entry->getRepName(),
$entry->getEmail1(),
$entry->getEmail2()
);
$i++;
}
return $response;
}
Guys just want to help you in this. I got following worked:
JSON
var mydata1 = { "page": "1", "total": 1, "records": "4","rows": [{ "id": 1, "cell": ["1", "cell11", "values1" ] },
{ "id": 2, "cell": ["2", "cell21", "values1"] },
{ "id": 3, "cell": ["3", "cell21", "values1"] },
{ "id": 4, "cell": ["4", "cell21", "values1"] }
]};
//Mark below important line. datatype "jsonstring" worked for me instead of "json".
datatype: "jsonstring",
contentType: "application/json; charset=utf-8",
datastr: mydata1,
colNames: ['Id1', 'Name1', 'Values1'],
colModel: [
{ name: 'id1', index: 'id1', width: 55 },
{ name: 'name1', index: 'name1', width: 80, align: 'right', sorttype: 'string' },
{ name: 'values1', index: 'values1', width: 80, align: 'right', sorttype: 'string'}],
Regards,
In my case, the problem was caused by the following line of PHP code (which was taken from jqGrid demo):
$responce->page = $page;
What is wrong here is that: I am accessing property page of object $responce without creating it first. This caused Apache to display the following error message:
Strict Standards: Creating default object from empty value in /home/mariusz/public_html/rezerwacja/apps/frontend/modules/service/actions/actions.class.php on line 35
And finally the error message used to be send to json reader within the script.
I fixed the problem by creating empty object:
$responce = new stdClass();
I don't think your ID is the correct type, I think it should be an int.
For the given json you really don't need the jsonreader settings. What you have listed is the defaults anyway, plus you don't have a subgrid in your json.
Try this:
{
"page":"1",
"total":1,
"records":"10",
"rows":[
{"id":1 ,"cell":["1","image","Chief Scout","Highest Award test","0"]},
{"id":2,"cell":["2","image","Link Badge","When you are invested as a Scout, you maybe eligible to receive a Link Badge. (See page 45)","0"]},
{"id":3,"cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]},
{"id":4,"cell":["4","image","Voyageur Scout Award","Voyageur Scout Award is the right after Pioneer Scout.","0"]},
{"id":5,"cell":["5","image","Voyageur Citizenship","Learning about and caring for your community.","0"]},
{"id":6,"cell":["6","image","Fish and Wildlife","Demonstrate your knowledge and involvement in fish and wildlife management.","0"]},
{"id":7,"cell":["7","image","Photography","To recognize photography knowledge and skills","0"]},
{"id":8,"cell":["8","image","Recycling","Demonstrate your knowledge and involvement in Recycling","0"]},
{"id":9,"cell":["10","image","Voyageur Leadership ","Show leadership ability","0"]},
{"id":10,"cell":["11","image","World Conservation","World Conservation Badge","0"]}
]}
I was working with WAMP 2.4, I was being crazy with this problem, I tried lot of things, like install previous versions of PHP and like 5.2, een I tried in Windows XP, and lots of jqGrid options.
Well thank to Oleg finally and Mariusz I find the only line:
$responce = new stdClass();
Before the use of $responce could solve all, and now my grid is works Great!!!
Thanks my friends.