I have this php script in a file named qnams.php that returns JSON:
include ("../include/database.php");
include ("../include/sessions.php");
$select = "SELECT column1,column2,column3,column4
FROM qnamtable WHERE USER = '$username'";
$query = mysqli_query($dbc, $select) or die(mysqli_error());
$out = array();
while ($row = $query->fetch_array()) {
$out[] = $row;
}
echo json_encode($out);
mysqli_free_result($query);
I found different posts on how to add the JSON directly into the dataTable, but was a little confused on how to proceed.
On my main page, I have this function at the bottom of the page:
$(function() {
$('#example1').dataTable({
"bPaginate": false,
"bLengthChange": true,
"bFilter": true,
"bSort": true,
"bInfo": true,
"sScrollY": "auto",
"sScrollCollapse": true,
"bAutoWidth": true
});
});
What do I need to add to this function to include the JSON with all the headers and data?
You need to use the ajax option of Jquery Datatables
ajax : {
url: 'the/path/to/php/file/with/jsondata'
}
You can use like below,
$(function() {
$('#example1').dataTable({
"processing": true,
"serverSide": true,
"ajax": "qnams.php" //set your php file location
"bPaginate": false,
"bLengthChange": true,
"bFilter": true,
"bSort": true,
"bInfo": true,
"sScrollY": "auto",
"sScrollCollapse": true,
"bAutoWidth": true
});
});
The html should be like below, Make sure the id should be example1
Set all the headers as below easily.
<table id="example1" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>column1</th>
<th>column2</th>
<th>column3</th>
<th>column4</th>
<th>column5</th>
<th>column6</th>
</tr>
</thead>
<tfoot>
<tr>
<th>column1</th>
<th>column2</th>
<th>column3</th>
<th>column4</th>
<th>column5</th>
<th>column6</th>
</tr>
</tfoot>
</table>
Check more information from here
First I would say you should use fetch_assoc, not fetch_array(). fetch_array() will include both the associated and the indexed array :
[{"0":"x","column1":"x","1":"y","column2":"y"}]
we just need
[{"column1":"x","column2":"y"}]
Then here is a fully automated script for populating a
<table id="example1"></table>
with any JSON as long as it is wellformed (as your PHP script seems to do) :
$.ajax({
url : 'qnams.php',
dataType : 'json',
success : function(json) {
//build the column definitions for titles and data-indexes
var columns = [];
Object.keys(json[0]).forEach(function(column) {
columns.push({ title: column, data: column })
})
$('#example1').dataTable({
data : json,
columns : columns,
"bPaginate": false,
"bLengthChange": true,
"bFilter": true,
"bSort": true,
"bInfo": true,
"sScrollY": "auto",
"sScrollCollapse": true,
"bAutoWidth": true
})
}
});
I assume you are using 1.10.x of dataTatables.
All of the other answers here were helpful, however in the end, I merely needed to acquire a recent version of jQuery DataTables. I was using newer code with an older template and that was a main issue affecting my results.
Related
I am using Codeigniter and data table. I am displaying the list. Now what I am doing is, I have to display all the list to the role id 1 and limited access on role id 2.
I tried in the controller which is working
if($this->session->userdata['login_session']['role']==1 ){
$action='<sel ect></select>';
}
else{
$action='';
}
View
This is also working.
<table id="emp-leadList">
<thead>
<tr>
<th>Name</th>
<?php if($this->session->userdata['login_session']['role']==1 ){ ?><th>Action</th><?php }?>
</tr>
</thead>
<tbody></tbody>
</table>
But I am getting the issue on the script. I want to know what code I have to use in the script
JS
$('#emp-leadList').DataTable( {
language: {
sLengthMenu: "Show _MENU_",// remove entries text
searchPlaceholder: "Search",
emptyTable: "No record found",
search:""
},
"autoWidth": false,
"ordering": false,// remove sorting effect from header
"processing": true,
//"serverSide": true,
"order":[],
"scrollX": true,
//"bInfo" : false,
"pageLength": 25,
"paging": true,
//"deferRender": true,
// "bDeferRender": true,
"ajax": {
"url" : baseUrl + "/Customer_control/emp_list",
"type" : "POST"
// "dataSrc": ""
},
"columns": [
{ "data": "name" },
{ "data": "action" }
],
"columnDefs": [
//{ width: '3%', targets: 0 },
{ width: '13%', targets: 0 },
{ width: '8%', targets: 1 }
]
});
Would you help me out in this?
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.
I am doing export functions using DataTable for a report.
I have created the example here:
https://jsfiddle.net/hn2gcken/140/
I have user input value in W2, which also updates the value of 4Tax. I have created a hidden span tag to get those values when I insert. But the values are still not showing in the excel/PDF format.
Jquery
var table = $('#example').DataTable( {
lengthChange: false,
dom: 'Bfrtip',
"bPaginate": false,
"paging": false,
"ordering": false,
"info": false,
"searching": false,
buttons: [ 'excel', 'pdf']
} );
table.buttons().container()
.appendTo( $('div.eight.column:eq(0)', table.table().container()) );
$("#w2").keyup(function () {
if (!isNaN(this.value) && this.value.length != 0)
{
$("#w2-span").text($(this).val());
$("#4tax-span").text($(this).val());
$("#4tax").val($(this).val());
$("#w2").attr('value', $(this).val())
}
});
I would be very grateful if anyone could help me.
Thanks!
I've have many processes using the same data that gets regular updates while a user is on a page. Now I want to use datatables to show this data.
I also use the ColReorder plugin.
The problem is that I don't understand how I can force datatables to 'reload' this local var with new data.
there is is also a bunch of definitions in the "aoColums" setting, using some of the datafields for images and so on.
I changed some of the data in the dat var. The tried to force datatables to put it in the table. No luck. I can't find a decent example or function in the api to use.
if I try to use oTable.fnClearTable() and the oTable.fnAddData(data) the data gets loaded, but somehow the ColReorder is not aplied.
myTable = $('#myTable').dataTable({
"aoColumns": [ ... ],
"aaSorting": [[1, 'asc']],
"aaData": data,
"sScrollY": 200,
"sScrollX": "100%",
"sScrollXInner": "150%",
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"sDom": 'R<"H"lfr>t<"F"ip>',
"iFixedColumns": 3,
"oColReorder": {
"aiOrder": [ 0, 8, 2, 3, 4, 5, 6, 7, 1, 9 ]
}
});
Any ideas?
EDIT
I've made a working jsFIddle with the whole problem explained. Take a look and have a go!
I read about your problem....i take another approach to your problem(it's always about dom manipulation xD)...my anwer it's not the smartest, but i think it works.
I put datatables manipulation inside a function, and add a div no the table
Then i call that function
On update i empty the div and add the same html that table have before datatbles manipulation and fill
Then a call the function to draw the whole datatables again, in that way ColReorder plugin works with the updated data.
PS: Here is the updated fiddle for more details : http://jsfiddle.net/aKuHM/5
Now the table looks like this:
<div class="Example" id="Example">
<table id="myTable" class="datatable">
<thead>
</thead>
<tbody>
</tbody>
<tfoot>
</tfoot>
</table>
</div>
And your JS its loading on the head and looks this way:
data = [
['cell1', 'cell2','cell3','cell4','cell5','cell6','cell17', 'cell8', 'cell9', 'cell10'],
['cell1', 'cell2','cell3','cell4','cell5','cell6','cell17', 'cell8', 'cell9', 'cell10'],
['cell1', 'cell2','cell3','cell4','cell5','cell6','cell17', 'cell8', 'cell9', 'cell10'],
];
function Saludos(){
$(function(){
myTable = $('#myTable').dataTable({
"aoColumns": [
{"sTitle":"col0", "bSearchable": false, "bVisible": true},
{"sTitle":"col1", "bSearchable": false, "bVisible": true},
{"sTitle":"col2", "bSearchable": true, "bVisible": true},
{"sTitle":"col3", "bSearchable": true, "bVisible": true},
{"sTitle":"col4", "bSearchable": true, "bVisible": true},
{"sTitle":"col5", "bSearchable": false, "bVisible": true},
{"sTitle":"col6", "bSearchable": true, "bVisible": true},
{"sTitle":"col7", "bSearchable": false, "bVisible": true},
{"sTitle":"col8", "bSearchable": true, "bVisible": true,
"mRender": function (data, type, row){
return '<b><i>'+ row[8] +'</i></b>';
}
},
{"sTitle":"col9", "bSearchable": false, "bVisible": false},
],
"aaSorting": [[8, 'asc']],
"aaData": data,
"sScrollY": 200,
"sScrollX": "100%",
"sScrollXInner": "150%",
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"sDom": 'R<"H"lfr>t<"F"ip>',
"iFixedColumns": 3,
"oColReorder": {
"aiOrder": [ 0, 8, 2, 3, 4, 5, 6, 7, 1, 9 ]
}
});
$('#updatebutton').click(function(){
updateTable();
});
});
}
Saludos();
function updateTable(){
data[1][8] = "even bolder";
$('.Example').empty();
$("#Example").html("<table id='myTable' class='datatable'><thead></thead> <tbody></tbody><tfoot></tfoot></table>");
Saludos();
console.log(data);
}
I've been looking around on the net for hours about this save scroll position for DataTables, but without any luck. At least not for my case.
According to datatables, to save the state of the scrollbar I need this line of code:
$(document).ready(function() {
var oTable = $('#example').dataTable( {
"sScrollY": "200px",
"sAjaxSource": "media/data/2500.txt",
"sDom": "frtiS",
"bDeferRender": true,
"bStateSave": true
} );
} );
But since I'm not having any text file with the data which I can parse it's not working. I'm fetching arrays in the table with PHP and MYSQL.
The "bStateSave": true does save every user input like filtering and sorting, except for the scrollbar.
Does anyone know how to solve this?
EDIT
Ok somehow I managed to get this working. It seems I had something on true, which shouldn't be. Now, with this "sDom" the savestate of scrolling works, but my GUI is gone...
EDIT
My initiation code is:
<!-- DATATABLES ENABLE INIT -->
<script>
<?php include ('js/datatables/ordernumhtml.js');?>
<?php include ('js/datatables/ordercurrency.js');?>
<?php include ('js/datatables/dataTables.scroller.min.js');?>
$(document).ready( function () {
$('#table1').dataTable( {
"sDom": "frtiS",
"bDeferRender": false,
"bStateSave": true,
"bAutoWidth": true,
"bInfo": true,
"sScrollX": "100%",
"bScrollCollapse": true,
"bScrollAutoCss": true,
"bScrollInfinite": false,
"sScrollY": "350px",
"bJQueryUI": true,
"bProcessing": true,
"aoColumns": [
{ "sType": "num-html" },
{ "sType": "numeric" },
null,
null,
null,
null,
null,
null,
{ "sType": "currency" },
null,
{ "bSortable": false }
]
} );
} );
</script>
And the solution was to rewrite the line:
"sDom": "frtiS", to:
"sDom": '<"H"fr>t<"F"iS>',
The "H" and the "F" represents the header and the footer for the jQueryUI.
A detailed description of the sDOM usage can be found here:
http://datatables.net/usage/options#sDom
The solution to save the scroll state is to set stateSave to true. To make this work one also needs to use dataTables.scroller.js
$(document).ready(function() {
$('#example').DataTable( {
ajax: "data/2500.txt",
deferRender: true,
dom: "frtiS",
scrollY: 200,
scrollCollapse: true,
stateSave: true
} );
} );
Check this : Scroller State Saving