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
Related
I'm trying to convert an existing "select" dropdown filter on a table generated via the DataTables library to be able to handle multiple options, and though I think I have it correct on the front-end Javascript, I'm having trouble figuring out how to handle it in the back-end PHP.
The below is from the script in the front-end view, which makes the Ajax Post request:
<script>
function generateTable() {
var oTable = $('#MyData').dataTable({
"aaSorting": [
[1, "desc"]
],
"aLengthMenu": [
[10, 25, 50, 100, 200],
[10, 25, 50, 100, 200]
],
"iDisplayLength": <?= $Settings->rows_per_page ?>,
'bProcessing': true,
'bServerSide': true,
'sAjaxSource': '/my/getData/path',
'fnServerData': function(sSource, aoData, fnCallback) {
// ...SNIP...
aoData.push({
"name": "some_status",
"value": $("#some_status").val()
});
$.ajax({
'dataType': 'json',
'type': 'POST',
'url': sSource,
'data': aoData,
'success': fnCallback
});
},
"aoColumns": [],
}).fnSetFilteringDelay().dtFilter([
// ...SNIP...
{
column_number: 4,
filter_default_label: "[<?= lang('some_status'); ?>]",
filter_type: "multi_select",
data: []
},
// ...SNIP...
], "footer");
}
</script>
I can confirm that the selected values are added to an array by console logging the $("#some_status").val(). So my assumption was that it would be passed to the backend as an array as well, but apparently not.
What actually happens is the first selection goes fine, but any subsequent selection clears the table, and only works if there's a single value selected, leaving me to believe that only the first selection is pushed to the aoData array.
In PHP I have:
$this->load->library('datatables');
$this->datatables
->select("id, date, reference_no, supplier, some_status")
->from('purchases');
$some_status = $this->input->post('some_status');
if ($some_status != '') {
$this->datatables->where('status', $some_status);
}
How do I handle the some_status value if it's an array, or how do I make sure it even is an array after it was pushed toaoData?
Any help will be appreciated!
EDIT:
To clarify, by console logging the result like below returns the correct selection as I add and remove selections from the multi-select dropdown:
console.log($("#some_status").val());
If I select "Top option" from the dropdown, I get:
[
"top_option"
]
When I then select "Another option" as well, I get:
[
"top_option", "another_option"
]
So the JS side is handling the multi-select, but I don't know if the below is correct, as it works only with a single select, nothing more:
$some_status = $this->input->post('some_status');
if ($some_status != '') {
$this->datatables->where('status', $some_status);
}
I am using Jquery data-tables plugin for my tables(using server-side scripting. but the alignment of pagination of data tables is going off after 6th page, please help me to sort this out.
pagination before 6th page:
pagination after 6th page:
$('#contacts').DataTable(
{
"order": [[ 0, "desc" ]],
"pageLength": 1,
"lengthChange": false,
"processing": true,
"serverSide":true,
"ajax":{
url:"abc.php",
type:"post"
},
"columnDefs": [
{"className": "dt-center", "targets": "_all"}
]
} );
$('input[type=search]').addClass('form-control round');
$("#contacts_filter").css('margin-right', '15px');
$("#contacts_filter").css('text-align', 'center');
$("#contacts_info").css('padding-left', '15px');
$("#contacts_info").css('font-size', '20px');
$("#contacts_paginate").css('padding-bottom', '10px');
$("#contacts_paginate").css('padding-top', '10px');
We have more than 200 000 records. Datatables take too much time to load.
here is code we have using
$(document).ready(function() {
var dataTable = $('#dataTables-example').DataTable( {
responsive: true,
"processing": true,
"serverSide": true,
'iDisplayLength': 25,
"aaSorting": [[ 7, "desc" ]],
"ajax": $.fn.dataTable.pipeline( {
url: 'report_list_ajax.php'
}),
"columnDefs": [
{"targets": 0, "orderable": false },
{"targets": 4, "orderable": false },
]
});
});
so we dont need jquery datatables load or initialize while page loading.
and jquery datatables initialize and execute when submitted the external form only.
i.e: "FROM" and "TO Date" selection and click on submit button, the datatables will load based on form inputs..
Datatables initialize and execute when external form submit:
$("#external_form_id").on("submit", function(){
//datatable initiate code...
});
Based on code above, datatable will not initiate until the external form trigger submit. This is what u want?
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 have a jqgrid that I'd like to populate with my json, but I can't get it to work. I think my json is fine since the grid is working when supplying the json as a string (datatype:jsonstring). The thing is, I don't get any errors from jqgrid, which makes it hard to debug.
Here's my json (validated with jslint):
{ "total":"1", "page":"1", "records":"5", "rows": [ {"id" :"1", "cell" :["Modulex", "", "", "", ""]}, {"id" :"2", "cell" :["Lemoltech", "", "", "", ""]}, {"id" :"3", "cell" :["Isothermic", "", "", "", ""]}, {"id" :"4", "cell" :["Renova", "", "", "", ""]}, {"id" :"5", "cell" :["Natart Juvenile", "", "", "", ""]} ] }
And here's my config
$("#list").jqGrid({
url:'/tempajax/',
datatype: 'json',
colNames:['Nom','Adresse','Ville','Tel','Courriel'],
colModel :[
{name:'company_name', index:'company_name', width:55},
{name:'address', index:'address', width:90},
{name:'city', index:'city', width:90},
{name:'telephone', index:'telephone', width:80},
{name:'email', index:'email', width:80},
],
autowidth: true,
pager: '#pager',
rowNum:10,
viewrecords: true,
gridview: true,
height: '100%'
});
This is my first post here, so I hope to have supplied enough information for you guys to help, if not just ask.
Thanks a lot for your help!
Your JSON result doesn't match with what you're configuring your jqGrid to consume.
Your jqGrid is expecting a JSON result that has company_name, address, city, telephone, and email as fields, but your data is bringing back id and cell, and even then it's nested inside the top json result, which has total, page, records, and rows. Either way, it's not lined up with your jqGrid.
I fixed my problem, the json was fine afterall. The server was throwing a 404 code, even though the output was good. This prevented jqGrid from even parsing the json. I hope this will be helpfull to others as well!