the problem here is the dataTables pagination is not working
this is the script i created that outputs json from the database
include( "../database.php" );
$q = $dbh->prepare("SELECT r.studid, r.firstname, r.middlename, r.lastname, r.Enrolling, c.courseid,c.code, s.status,s.dateapproved,s.approvedby FROM pcc_registration r, pcc_courses c, pcc_studentsubj s WHERE c.courseid= r.Enrolling AND s.studentid=r.studid AND r.status=? AND s.status=? GROUP BY r.studid");
$q->execute(array(1,2));
$rows = array();
$i = 1;
while ($r = $q->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT, PDO::FETCH_COLUMN)){
$rows[] = array(
"DT_RowId" => "row_".$i,
"reg" => array(
"studid" => $r[0],
"firstname" => $r[1],
"middlename" => $r[2],
"lastname" => $r[3],
"course" => $r[6],
"dateapproved" => $r[8],
"approvedby" => $r[9]
),
);
$i++;
}
$rt = (STRING) $q->rowCount();
$data = array(
"draw" => 2,
"recordsTotal" => $rt,
"recordsFiltered" => $rt,
"data" => $rows
);
echo json_encode($data);
and this is the javascript that outputs the json encoded data to the page
(function($) {
$(document).ready(function() {
$('#dataTables-example').DataTable( {
processing: true,
serverSide: true,
ajax: {
url: "includes/php/approvedSched.php",
type: "POST"
},
"deferRender": true,
columns: [
{data: "reg.studid"},
{data: "reg.lastname"},
{data: "reg.firstname"},
{data: "reg.middlename"},
{data: "reg.course"},
{data: "reg.dateapproved"},
{data: "reg.approvedby"},
{data: "reg.studid"},
],
tableTools: {
sRowSelect: "os",
aButtons: [
// {sExtends: "editor_edit", editor: editor},
// {sExtends: "editor_remove", editor: editor}
]
}
} );
});
}(jQuery));
any answer or solution to this problem is appreciated =)
http://datatables.net/manual/server-side
http://coderexample.com/datatable-demo-server-side-in-phpmysql-and-ajax/
this links is a better help for custom server side with mySQL
Where is the problem exactly? Is it just the DataTable pagination, or is it related with the MySQL query? I mean, does it show the rows and the problem is just the pagination, or it doesn't show anything at all?
I had some issues 'transferring' the query result from php to js as JSON (I'm a complete web programming noob), but DataTables' pagination didn't gave me any problem...
Related
I am new to DataTables Server Side Processing.
How can I join/combine two database column (db) in one datatables column (dt) using the server side script ? I tried:
$columns = array(
array( 'db' => 'id', 'dt' => 'id' ),
array( 'db' => array('firstname', 'lastname'),'dt' => 'priest' )
);
and it's NOT working. What is the right what to do that? Thank you!
I'm using DataTables-1.10.16.
You can also do it server side and then hide the column you don't want in js.
For example let's say you have a table with 3 columns: id, name and link.
To combine the link into the name do:
In html (header and footer) show both columns (we will hide the column dynamically in javascript):
<th>#</th><!--this is column 0 with id-->
<th>name</th><!--this is column 1 with name including a tag-->
<th>link</th><!--this is column 2 with link-->
In javascript:
$(document).ready(function() {
$('#table_id').DataTable(
"processing": true,
"serverSide": true,
"ajax": {
"url": "ajax.php"
},
"order": [[ 0, "asc" ]],//ordering by the id (usefull)
{"columnDefs": [
{ "visible": false, "targets": [ 0 ] },//hiding the id
{ "visible": false, "targets": [ 2 ] }//hiding the link column
]
});
});
In the ajax php script also describe both columns:
$columns = array(
array( 'db' => 'id', 'dt' => 0),
array(
'db' => 'name',
'dt' => 1,
'formatter' => function( $d, $row ) {
return ''.$d.'';
}
),
array( 'db' => 'link', 'dt' => 2 )
);
Sorry for late answer,
Actually in demo spss.php class you cannot merge them but we have a solution,
Which is using "Column Render"
Go to Server Side Processing file and
write a something like that (16 just assuming if you've 5 column u should write 6)
array( 'db' => 'database column', 'dt' => 16 )
Then go to the client;
$(document).ready(function() {
$('#example').DataTable( {
"columnDefs": [
{
// The `data` parameter refers to the data for the cell (defined by the
// `data` option, which defaults to the column being worked with, in
"render": function ( data, type, row ) {
return data +' ('+ row[16]+')';
},
"targets": 11
},
//This is makes db 16 row nonvisible
{ "visible": false, "targets": [ 16 ] }
],
} );
} );
"Targets":11 means i would like add something to 11. column.
I created a table in my database that has 3 columns on it, the third column is a Download File column that has a text on it that can redirect to a file in my uploads folder. Any ideas on how to create the file download column?
<script type="text/javascript">
var $table = $('#table');
$table.bootstrapTable({
url: 'list-user.php',
search: true,
pagination: true,
buttonsClass: 'primary',
showFooter: true,
minimumCountColumns: 2,
columns: [{
field: 'first',
title: 'Date',
sortable: true,
},{
field: 'last',
title: 'Title',
sortable: true,
}, {
field: 'file',
title: 'Download',
sortable: true,
}],
});
List-user file
<?php
require 'db.php';
$sqltran = mysqli_query($con, "SELECT * FROM user ")or die(mysqli_error($con));
$arrVal = array();
$i=1;
while ($rowList = mysqli_fetch_array($sqltran)) {
$name = array(
'num' => $i,
'first'=> $rowList['fname'],
'last'=> $rowList['lname']
);
array_push($arrVal, $name);
$i++;
}
echo json_encode($arrVal);
mysqli_close($con);
?>
You don't have an array key/value for your file column. Hard to know where you store the filename without seeing your database structure, but replace download_path_column_name with the correct column name.
$name = array(
'num' => $i,
'first'=> $rowList['fname'],
'last'=> $rowList['lname'],
'file' => 'Download'
);
I am trying to create a dependent combobox system in my Yii application.
First combobox is populated with States and the second one is dynamically generated with ajax and renderPartial() method.
Code below:
View
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => $adMulti,
'attribute' => 'state_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData(State::model()->findAll(), 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
// JS code to execute on 'select' event, the selected item is
// available through the 'item' variable.
'onSelect' => 'getCities(item.value);',
// If false, field value must be present in the select.
// Defaults to true.
'allowText' => false,
),
// Options passed to the text input
'htmlOptions' => array(
'style' => 'height: 36px',
),
));
?>
<script type="text/javascript">
function getCities(state) {
$.ajax({
url: '<?php echo $this->createUrl('ad/ajaxCities'); ?>',
data: {state_name: state},
type: 'POST',
success: function (data) {
$('#city_id-carrier').html(data);
}
});
}
</script>
<div id="city_id-carrier" class="textboxes"></div>
AdController
public function actionAjaxCities()
{
$stateName = isset($_POST['state_name']) ? $_POST['state_name'] : FALSE;
if ($stateName) {
$state = State::model()->findByAttributes(array(
'name' => $stateName
));
$stateId = $state->id;
$cities = City::model()->findAllByAttributes(array(
'state_id' => $stateId
));
$this->renderPartial('_cities', array(
'cities' => $cities,
'stateId' => $stateId
), FALSE, TRUE
);
}
}
_cities.php
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => AdMulti::model(),
'attribute' => 'city_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData($cities, 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
// JS code to execute on 'select' event, the selected item is
// available through the 'item' variable.
// 'onSelect' => 'getLocalities(item.value);',
// If false, field value must be present in the select.
// Defaults to true.
'allowText' => false,
),
));
?>
The code is working and creating the combobox for the first time. But when I change the value in state combobox, something weird happens. A new combobox is created, but the values shown are still from the first combobox generated.
I am getting an error "TypeError: this.input is undefined" in Firebug Console.
I tried creating unique id for combobox using uniqid() but it isn't affecting the id of select element of the combobox.
If I change
$('#city_id-carrier').html(data)
to
$('#city_id-carrier').append(data)
it is working well but with multiple combobox generated.
Any ideas/suggestions to make this work?
I've found a solution to get this working. Instead of creating the combobox dynamically, place the combobox once and then populate it dynamically upon each request. Much like dependent dropdown.
A combobox is a combination of a dropdown and textbox. So, note down the id of the hidden dropdown and update it upon ajax update.
Code:
View:
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => $adMulti,
'attribute' => 'state_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData(State::model()->findAll(), 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
// JS code to execute on 'select' event, the selected item is
// available through the 'item' variable.
'onSelect' => 'getCities(item.value);',
// If false, field value must be present in the select.
// Defaults to true.
'allowText' => false,
),
));
?>
<script type="text/javascript">
function getCities(state) {
$.ajax({
url: '<?php echo $this->createUrl('ad/ajaxCities'); ?>',
data: {state_id: state},
type: 'POST',
beforeSend: function() {
$('#AdMulti_city_id_combobox').val(''); // emptying textbox in case a value is previously selected.
},
success: function (data) {
$('#AdMulti_city_id').html(data); // populating the hidden dropdown.
}
});
}
</script>
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => $adMulti,
'attribute' => 'city_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData(array(''), 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
'allowText' => false,
),
));
?>
AdController
public function actionAjaxCities()
{
$stateName = isset($_POST['state_id']) ? $_POST['state_id'] : FALSE;
if ($stateName) {
$state = State::model()->findByAttributes(array(
'name' => $stateName
));
$cities = City::model()->findAllByAttributes(array(
'state_id' => $state->id
));
$data = CHtml::listData($cities, 'id', 'name');
foreach ($data as $id => $name) {
echo CHtml::tag('option', array('value' => $id),
CHtml::encode($name), TRUE);
}
}
}
I am using Yii framework on a project and i am using an extension which uses select2 jquery. I am unable to grasp how the implementation for ajax works with this extension or the select2.
My ajax call returns the following json.
[
{"id":"1", "text" : "Option one"},
{"id":"1", "text" : "Option one"},
{"id":"1", "text" : "Option one"}
]
The yii extension enfolds the select2 extension as below
$this->widget('ext.select2.ESelect2', array(
'name' => 'selectInput',
'ajax' => array(
'url'=>Yii::app()->createUrl('controller/ajaxAction'),
'dataType' => 'json',
'type' => 'GET',
'results' => 'js:function(data,page) {
var more = (page * 10) < data.total; return {results: data, more:more };
}',
'formatResult' => 'js:function(data){
return data.name;
}',
'formatSelection' => 'js: function(data) {
return data.name;
}',
),
));
I found a related question from this Question! The link to the extension am using is YII select2 Extention!
So a week later i merged with the answer to this question.
First let me highlight how the select2 ajax or in my case the Yii ESelect Extension.
The ajax options for jquery are the same as for the Eselect Extention i.e. url,type and datatype altho there is a slight difference on the format returned after successfully querying.
As for the result set for Eselect/select2 expects two parameters to be returned. that is
id : data.myOptionsValue;
text : data.myOptionText;
Reference :: https://select2.github.io/options.html#ajax
if we want to customize the format for the result set that is retured we can go a head and extend the plugin by using
'formatResult' => 'js:function(data){
return data.name;
}',
'formatSelection' => 'js: function(data) {
return data.name;
}',
I also had an issue getting my head around how the extention was quering. A look around and i realised that we have two datatype jsonp and json these two datatypes will handle data differently.
Jsonp (json padding) allows sending query parameters when querying. As for my case i am not passing any other parameters e.g an authkey e.t.c. In my case i changed the datatype to json and returning a json with id and text as results. See below my working snippet.
echo CHtml::textField('myElementName', '', array('class' => 'form-control col-lg-12'));
$this->widget('ext.select2.ESelect2', array(
'selector' => '#myElementName',
'options' => array(
'placeholder' => 'Search ..',
'ajax' => array(
'url' => Yii::app()->createUrl('controller/ajaxAction'),
'dataType' => 'json',
'delay' => 250,
'data' => 'js: function(term) {
return {
q: term,
};
}',
'results' => 'js: function(data){
return {results: data }
}',
),
),
));
I am having a very strange issue creating a piechart in Flot with data from PHP.
It seems to be drawing incorrectly, and I can't figure out why.
My PHP code (for testing) is:
echo json_encode(
'[{ label: "Series1", data: 10},
{ label: "Series2", data: 3},
{ label: "Series3", data: 9},
{ label: "Series4", data: 7},
{ label: "Series5", data: 8},
{ label: "Series6", data: 17}]'
);
My JS file is:
$.ajax({
type:'GET',
dataType:"json",
url:'../phpfile.php',
success: function(data) {
console.log(data);
$.plot($("#piechart"),data,{
series: {
pie: {
show: true
}
}
});
}
});
The consol log shows:
[{ label: "Series1", data: 10},
{ label: "Series2", data: 3},
{ label: "Series3", data: 9},
{ label: "Series4", data: 7},
{ label: "Series5", data: 8},
{ label: "Series6", data: 17}]
Which I thought was the correct format for flot...
But it graphs like this:
Does anyone have any ideas?
I believe your JSON currently is invalid, at the moment, you're trying to parse an JSON String, into a JSON String (If you get what I mean!) Currently, when I echo out from the PHP end with your echo'ed json_encode(), I'm provided with:
"[{ label: \"Series1\", data: 10},\r\n{ label: \"Series2\"]"
Furthermore, I would use PHP Arrays to encode JSON, like below:
<?php
$arr = array(
array(
"label" => "Series1",
"data" => 10
),
array(
"label" => "Series2",
"data" => 3
),
array(
"label" => "Series3",
"data" => 9
),
array(
"label" => "Series4",
"data" => 7
),
array(
"label" => "Series5",
"data" => 8
),
array(
"label" => "Series7",
"data" => 17
)
);
echo json_encode( $arr );
?>
PHP json_encode() does accept mixed variable types, but it's most popularly used with PHP arrays.
With the above, I'm able to construct the PIE chart successfully: