As per the document here ,i have implemented the server side code.
JS code
$('#datatable_paging').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "#### my php file path ####",
});
I am getting JSON data as
{
"sEcho": 0,
"iTotalRecords": 19,
"iTotalDisplayRecords": "19",
"aaData": [
["1", "peter", "peter#gmail.com"],
["2", "john", "john#yahoo.com"],
["3", "raj", "raj#in.com"],
["4", "selvin", "selvin#gmail.com"],
["5", "ismail", "ismail#gmail.com"],
["6", "muadth", "muad#hotmail.com"],
["7", "ahmed", "ahmed#gmail.com"],
.....
]
}
Now i need to display this JSON result in below table with Datatable pagination
HTML code
<table id="datatable_paging">
<thead>
<tr>
<th>Id </th>
<th>Name</th>
<th>E-mail</th>
</tr>
</thead>
</table>
People answering this are overthinking this way too much. Datatables will handle the output without any fancy looping/assigning/etc when you set the options correctly. Assuming your JSON return is proper as described in the spec:
HTML:
<table id="datatable_paging"></table>
Then the jQuery:
var oTable = $('#datatable_paging').dataTable( {
"bDestroy":true,
"bStateSave": true,
"aaSorting": [[1, "asc"]],
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "#### my php file path ####",
"bJQueryUI": true,
"bAutoWidth": false,
"bFilter":true,
"bLengthChange": true,
"bPaginate": true,
"bSort": true,
"iDisplayLength": 10,
"bInfo": true,
"sPaginationType": "full_numbers",
"aoColumns": [
{ "sTitle": "Id", "sWidth": "33%"},
{ "sTitle": "Name", "sWidth": "33%"},
{ "sTitle": "Email", "sWidth": "33%"}
]
})
The paging, etc is going to be setup properly, assuming that your PHP source is correctly filtering as it should. If, for example, you find that you're getting 19 results when you should be getting 10, you'd know that the problem is at your source, not here in the jQuery. In your example, the source says it's returning 19 total result out of 19 and bPaginate hasn't been specified, so that would be why the paging isn't working. aoColumns setups your head, no need to do in HTML unless you really want to. The other functions are well-documented on the datatables site, though ask questions if you're confused.
You could just loop though the 'aaData' and add a new row directly with fnAddData.
Check here for example: http://datatables.net/examples/api/add_row.html
Edit: A example for you as well.
var aaData = theVariableHoldingTheJsonObject.aaData;
$("#datatable_paging").dataTable().fnAddData ( aaData )
That's basically it
It seems like you should send back a correct "sEcho" variable in JSON.
It is information that DataTables needs to know about the data being sent back, in order to be able to render. You need to pass back to DataTables the value that was sent.
sEcho is described here: http://datatables.net/usage/server-side
So to get your example works change "sEcho" to 1 or better write like this:
"sEcho": int(request.vars['sEcho']) #python code
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.