I am doing ajax pagination in cakephp 3.2
I have done code for forward move of pagination, by getting the last id .
If i want to go backward ,the pagination will not work ,i know .
How can i do it in a proper way so that it will work for both direction as well as direct click on any pagination index.
Below i have attached some of my codes ,which is working properly only for forward move of pagination.
I know the code won't work for backward move.
How can i do it?
///////////////////////////////////PAGINATION STARTS HERE/////////////////////////////////////////////////
if(isset($_POST["page"])){
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH); //filter number
if(!is_numeric($page_number)){die('Invalid page number!');} //incase of invalid page number
}else{
$page_number = 1; //if there's no page number, set it to 1
}
$item_per_page=5;
$get_total_rows = $this->Orders->find('all')->where($condition)->count(); //hold total records in variable
$total_pages = ceil($get_total_rows/$item_per_page);
$page_position = (($page_number-1) * $item_per_page);
if($page_number>1)
{
$condition[] = ['Orders.id >' => $_POST["lastId"]];
}//this one fetch all list greater than last id
$Lists = $this->Orders->find('all')->where($condition)->order(['Orders.id' => 'ASC'])->limit($item_per_page)->toArray();
Thank you
Your Controller Action code should be
$this->paginate = [
'order'=>[
'field_name'=>'desc'
]
];
$condition = [];
$query = $this->YourModel->find()->where($conditions);
$this->set('records', $this->paginate($query));
In view your code should be for listing part only, I dont know whta is your HTML structure but you can follow this, and dont forget about id=pagination_list_container in parent of your table and pagination link code.
<div class="panel-body" id="pagination_list_container">
<div class="inner-spacer">
<table class="table table-striped table-hover margin-0px">
<thead>
<tr>
<th><?php echo $this->Paginator->sort('field_1', 'Column 1') ?></th>
<th><?php echo $this->Paginator->sort('field_2', 'Column_2') ?></th>
<th><?php echo $this->Paginator->sort('field_3', 'Column_3') ?></th>
</tr>
</thead>
<tbody>
<?php
if (empty($records->toArray())) {
?>
<tr><td colspan="100%" class="text-danger text-center">No record found</td></tr>
<?php
} else {
foreach ($records as $record):
?>
<tr>
<td><?php echo $record->field_1 ?></td>
<td><?php echo $record->field_2; ?></td>
<td><?php echo $record->field_3; ?></td>
</tr>
<?php endforeach; ?>
<?php } ?>
</tbody>
</table>
</div>
<div class="row">
<div class="col-md-6">
<ul class="pagination">
<?php
$this->Paginator->templates([
'current' => '<li class="active"><a>{{text}}</a></li>',
'number' => '<li>{{text}}</li>'
]);
echo $this->Paginator->prev('«');
echo $this->Paginator->numbers();
echo $this->Paginator->next('»');
?>
</ul>
</div>
<div class="col-md-6 text-right">
<div class="mt30">
<?php
echo $this->Paginator->counter(
'Page {{page}} of {{pages}}, showing {{start}} to {{end}} of {{count}}'
);
?>
</div>
</div>
</div>
</div>
Make AJAX behaviour in your view
You have to Apply Some Javascript event for ajax behaviour into #pagination_list_container
$(document).ready(function(){
$("document").on('click','#pagination_list_container .pagination li a, #pagination_list_container table th > a', function(e){
e.preventDefault();
var link= $(this).attr('href');
if(link!="")
{
$("#pagination_list_container").load(link+ "#pagination_list_container", function(){
console.log("data loaded");
})
}
return false;
});
});
Related
I'm using VueJS CDN in my PHP project.
I created a loop (foreach) which fetches records and displays them in a table. I would like to load up a modal when I click on a button inside the table but it's not working or giving me any error as to why it isn't working.
Taking the button outside the table/loop works fine and accesses the VueJS method.
var app_admin = new Vue({
el: '#orders',
data: {
},
mounted: function(){
},
methods: {
getOrderDetails( order_id, order_no ){
alert( order_id +' | '+ order_no );
},
}
});
<div class="page-content-inner is-webapp" id="orders" v-cloak>
<?php
$get_orders = $db_con->prepare("SELECT oid, order_no, rider, created_at, status FROM ". ODS ." ORDER BY created_at DESC");
$get_orders->execute();
if ( $get_orders->rowCount() > 0 ){
?>
<div class="table-wrapper" data-simplebar>
<table id="empty-datatable" class="table is-datatable is-hoverable table-is-bordered">
<thead>
<tr>
<th>Order_No</th>
</tr>
</thead>
<tbody>
<?php
$rows = $get_orders->fetchAll();
foreach ( $rows as $row ){
?>
<tr>
<td>
<?php
if ( $row['status'] == 'Waiting' ){
?>
<button #click="getOrderDetails('show', <?=$row['oid'].', '.$row['order_no']; ?>)">Click</button>
<?php
}
?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<div id="paging-first-datatable" class="pagination datatable-pagination">
<div class="datatable-info">
<span></span>
</div>
</div>
<?php
} else {
?>
<div class="col-12">
<div class="message is-primary">
<a class="delete"></a>
<div class="message-body">No Record Found!</div>
</div>
</div>
<?php
}
?>
<!-- PANEL -->
<?php
//include 'panels/Orders.All.OrderDetails.Panel.php'; // Order Details
?>
<!--// PANEL -->
</div>
The button doesn't access the getOrderDetails function while in the loop but taking it out works. What could I be doing wrong?
I have a jQuery dataTable that depending on the option you select in a previous Select shows you some data or others. By default it shows those of the first option and so far everything is correct.
The problem comes when I select the second option, that the dataTable seems to be unconfigured and shows me all the results in a row without respecting the Paginate, also if I try to sort by name or another field it will show me the first option again. The same is also true if I try to change the table page.
I don't know where the error is.
I attach some images as a sample:
First option (everything works perfect): image
On select second option: image , image2
If i try to click on tabs 1 to 7 or p.ex. order the column
Universitatautomatically shows this (results of the first selector but without respecting the design of the table) image
First option selector code:
<div class="panel-body">
<div class="tab-content">
<div class="tab-pane fade in active no-info" id="tab1default">
<?php if($isAdmin){ ?>
<input type="hidden" id="niuProfessor" value="<?php echo $niu; ?>">
<div class="padding-bottom-20">
<select id="selectIfAdmin">
<option id="mineAdmin" value="mineAdmin">Les meves Universitats</option>
<option id="allAdmin" value="allAdmin">Totes les Universitats</option>
</select>
</div>
<!--<div id="showByGrau" class="padding-bottom-20" >
<select id="selectGrauAdmin">
<option value="-1">Tots els graus </option>
<?php foreach($degrees as $degree): ?>
<option value="<?php echo $degree->codiEstudis; ?>"><?php echo $degree->nomGrau; ?></option>
<?php endforeach; ?>
</select>
</div>-->
<?php } ?>
<div id="acordsTeacherAdmin" class="table-responsive">
<table class="table table-hover cell-border display compact" id="dev-table">
<thead>
<tr>
<th>Universitat</th>
<!-- <th>Grau</th>-->
<th>Places</th>
<th>Mesos</th>
<th>Període</th>
<!--<th>Assignatures</th>-->
<th><em class="fa fa-cog"></em></th>
</tr>
</thead>
<tbody id="taulaAcordsCoordinador">
<?php foreach ($agree as $ag): ?>
<tr >
<td><?php echo $ag->nomUniversitat; ?></td>
<!--<td><?php echo $ag->nomGrau; ?></td>-->
<td><?php echo $ag->plaçes; ?></td>
<td><?php echo $ag->mesos; ?></td>
<td><?php echo $ag->període; ?></td>
<!--<td align="center">
Opinar
</td>-->
<td align="center">
Publicar / Acord
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
</div>
</div>
<div id="debug">
</div>
</div>
</div>
Second option code (TaulaAcordsCoordinador.php):
<?php foreach ($agree as $ag): ?>
<tr >
<td><?php echo $ag->nomUniversitat; ?></td>
<td><?php echo $ag->plaçes; ?></td>
<td><?php echo $ag->mesos; ?></td>
<td><?php echo $ag->període; ?></td>
<!--<td align="center">
Opinar
</td>-->
<td align="center">
Publicar / Acord
</td>
</tr>
<?php endforeach; ?>
EventListener:
,$(document).on("change", "#selectIfAdmin", function(e){
e.preventDefault();
var data = {};
data.niu = $("#niuProfessor").val();
data.filtre = $(this).val();
filtrarAcordsAdmin(data);
})
Function with Ajax call:
function filtrarAcordsAdmin(data){
$.ajax({
type: "POST",
url: "perfil.php/" + "filtrarAcordsAdmin",
data: {"data":JSON.stringify(data)},
success: function(t, e, c) {
$("#taulaAcordsCoordinador").html(t);
/*if(data.filtre === "allAdmin"){$("#showByGrau").css('display','block');}
else{$("#showByGrau").css('display','none');}*/
},
error: function(t, e) {
}
})}
Perfi.php code:
case 'filtrarAcordsAdmin':
$actionName = "filtrarAcordsAdmin";
$data['data'] = $_POST['data'];
array_push($parameters,$data);
break;
filtrarAcordsAdmin controller:
public function filtrarAcordsAdmin($parameters){
$data = json_decode($parameters[0]['data']);
require_once 'models/TeachersModel.php';
require_once 'models/ConvenisModel.php';
$teachersModel = new TeachersModel();
$convenisModel = new ConvenisModel();
if($data->filtre == 'mineAdmin'){
$agree = $teachersModel->getAgreementsTeacher($data->niu);
}elseif ($data->filtre == 'allAdmin'){
$agree = $convenisModel->getConvenis();
}
$teachersModel->disconnect();
$convenisModel->disconnect();
$route = $this->view->show("TaulaAcordsCoordinador.php");
include($route);
}
Both functions getConvenis() and getAgreementsTeacher() are functions of a model that returns de result of a query into the BD like that:
public function getConvenis(){
try {
$consulta = $this->db->prepare('SELECT uni.nomUniversitat, uni.idUniversitat, es.nomGrau,co.codiConveni,co.codiCentreEstudis,ce.plaçes,ce.mesos,ce.període
FROM centreestudis ce, universitat_estudisuab un,universitats uni,estudisuab es,conveni co
WHERE ce.codiUniEstudis = un.codiUniEstudis
AND uni.idUniversitat = un.idUniversitat
AND un.codiEstudis = es.codiEstudis
AND co.codiCentreEstudis = ce.codiCentreEstudis
ORDER BY uni.nomUniversitat');
$consulta->execute();
$obj = $consulta->fetchAll(PDO::FETCH_OBJ);
} catch (Exception $e) {
}
return $obj;
}
public function getAgreementsTeacher($niu){
try {
$consulta = $this->db->prepare('SELECT ce.plaçes, ce.mesos, ce.període , un.nomUniversitat ,un.idUniversitat,co.codiConveni, eu.nomGrau
FROM professorscentre pr, centreestudis ce, universitat_estudisuab ue, estudisuab eu, universitats un, conveni co
WHERE pr.niuProfessor = ?
AND ce.codiCentreEstudis = pr.codiCentreEstudis
AND ue.codiEstudis = eu.codiEstudis
AND ce.codiUniEstudis = ue.codiUniEstudis
AND un.idUniversitat = ue.idUniversitat
AND co.codiCentreEstudis = ce.codiCentreEstudis
ORDER BY un.nomUniversitat');
$consulta->execute(array($niu));
$obj = $consulta->fetchAll(PDO::FETCH_OBJ);
return $obj;
} catch (Exception $e) {
}
}
I've been creating a CMS blog and this is one of the pages that accessible by the admins. I'm trying to implement pagination in it.
As you can see, it shows the latest six posts in the first page with the IDs from 1 to 6, but when I click on the forward button, it shows the IDs 1 and 2 again for the other posts in which it should be 7 and 8. Could someone tell me what's causing this bug?
First page
Second page
<!-- Right Side Area Start -->
<div class="col-lg-10">
<div class="card-body bg-info">
<h2 class="large-georgia-white-bold">Top Posts</h2>
</div>
<table class="table table-striped table-hover">
<thead class="thead-dark small-times-white">
<tr>
<th>No.</th>
<th>Title</th>
<th>Date&Time</th>
<th>Author</th>
<th>Comments</th>
<th>Details</th>
</tr>
</thead>
<?php
$SrNo = 0;
global $ConnectingDB;
// Query When Pagination is Active i.e Dashboard.php?page=1
if (isset($_GET["page"])) {
$Page = $_GET["page"];
if ($Page==0||$Page<0) {
$ShowPostFrom=0;
}else{
$ShowPostFrom=($Page*6)-6;
}
$sql ="SELECT * FROM posts ORDER BY id desc LIMIT $ShowPostFrom,6";
$stmt=$ConnectingDB->query($sql);
}
// The default SQL query
else{
$sql = "SELECT * FROM posts ORDER BY id desc LIMIT 0,6";
$stmt=$ConnectingDB->query($sql);
}
while ($DataRows=$stmt->fetch()) {
$PostId = $DataRows["id"];
$DateTime = $DataRows["datetime"];
$Author = $DataRows["author"];
$Title = $DataRows["title"];
$SrNo++;
?>
<tbody class="small-times-black">
<tr>
<td><?php echo $SrNo; ?></td>
<td><?php echo $Title; ?></td>
<td><?php echo $DateTime; ?></td>
<td><?php echo $Author; ?></td>
<td>
<?php $Total = ApproveCommentsAccordingtoPost($PostId);
if ($Total>0) {
?>
<span class="badge badge-success">
<?php
echo $Total; ?>
</span>
<?php } ?>
<?php $Total = DisApproveCommentsAccordingtoPost($PostId);
if ($Total>0) { ?>
<span class="badge badge-danger">
<?php
echo $Total; ?>
</span>
<?php } ?>
</td>
<td> <a target="_blank" href="FullPost.php?id=<?php echo $PostId; ?>">
<span class="btn btn-info">Preview</span>
</a>
</td>
</tr>
</tbody>
<?php } ?>
</table>
<!-- Right Side Area End -->
<!-- Pagination -->
<nav>
<ul class="pagination pagination-lg">
<!-- Creating Backward Button -->
<?php if( isset($Page) ) {
if ( $Page>1 ) {?>
<li class="page-item">
«
</li>
<?php } }?>
<?php
global $ConnectingDB;
$sql = "SELECT COUNT(*) FROM posts";
$stmt = $ConnectingDB->query($sql);
$RowPagination = $stmt->fetch();
$TotalPosts = array_shift($RowPagination);
//echo $TotalPosts."<br>";
$PostPagination=$TotalPosts/6;
$PostPagination=ceil($PostPagination);
//echo $PostPagination;
for ($i=1; $i <= $PostPagination ; $i++) {
?>
<li class="page-item">
<?php echo $i; ?>
</li>
<?php } ?>
<!-- Creating Forward Button -->
<?php if ( isset($Page) && !empty($Page) ) {
if ($Page+1 <= $PostPagination) {?>
<li class="page-item">
»
</li>
<?php } }?>
</ul>
</nav>
</div>
</div>
</section>
<!-- Main area end -->
Your script always reassigns $SrNo = 0 when the page is loaded and starts over. You should add the page * 6 value to it so it becomes aware of the offset. In fact, you're already using that logic for $ShowPostFrom, so you can simply assign the same value to $SrNo and it should work:
if ($Page==0||$Page<0) {
$ShowPostFrom=0;
}else{
$ShowPostFrom=($Page*6)-6;
}
$SrNo = $ShowPostFrom; // <- this is what you should add
If you don't mind modifying $ShowPostFrom, you can drop $SrNo completely and just use $ShowPostFrom to show the number.
I can't load mysql data to the view by selecting please help me to find out the error. thank you.
View
<div class="grid">
<div class="row">
<?php $this->load->view('admin/admin_topmenu.php'); ?>
</div>
<div class="row">
<div class="span10 box" style="padding: 10px;">
<p>Recent Messages</p>
<table class="table hovered">
<thead>
<tr class="selected">
<th class="text-left">Name</th>
<th class="text-left">Email</th>
<th class="text-left">Phone</th>
<th class="text-left">Message</th>
</tr>
</thead>
<tbody>
<?php echo form_open('admin_forms/inbox') ?><!-- start of the form -->
<?php if(isset($records)) : foreach($records as $row) : ?>
<tr>
<td class="right"><?php echo $row->contactus_name; ?></td>
<td class="right"><?php echo $row->contactus_email; ?></td>
<td class="right"><?php echo $row->contactus_phone; ?></td>
<td class="right tertiary-text-secondary text-justify"><?php echo $row->contactus_comment; ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
<?php echo form_close(); ?><!-- END of the form -->
</tbody>
<tfoot></tfoot>
</table>
</div>
<div class="span3">
<nav class="sidebar light">
<ul>
<li>
<a href="#">
<i class="icon-home"></i>
Inbox <strong>(5)</strong>
</a>
</li>
<li>
<a href="#">
<i class="icon-home"></i>
Send
</a>
</li>
<li>
<a href="#">
<i class="icon-home"></i>
Newsletter/Ad
</a>
</li>
</ul>
</nav>
</div>
</div>
controller
<?php class Admin extends CI_Controller {
function index()
{
}
function inbox()
{
$data = array();
if($query = $this->mod_contactus->get_records())
{
$data['records'] = $query;
}
$this->load->view('admin/admin_messages',$data);
}
}
model
<?php
class Mod_contactus extends CI_Model
{
function get_records()
{
$query = $this->db->get('tbl_contactus');
return $query->result();
}
function add_record($data)
{
$this->db->insert('tbl_contactus', $data);
return;
}
function update_record()
{
}
}
When I go to the Source Code of the page click the form post method it gives me 404 Page Not Found error.
I'm assuming you are able to get to the page and you are getting the error upon form submission. Unless you have special routes setup in your application/config/routes.php file I believe by changing this line in your view
<?php echo form_open('admin_forms/inbox') ?><!-- start of the form -->
to
<?php echo form_open('admin/inbox') ?><!-- start of the form -->
would do the trick.
I say this because your controller's name is Admin and in order to call it (by default) you would have to use admin in the URL and not admin_forms.
You need to fetch the results,
So the line:
Actually, your variable $records is a resource, not a result set.
<?php if(isset($records)) : foreach($records as $row) : ?>
So, please use this resource and then fetch the records.
It should become:
<?php if(isset($records)) : foreach($records->result as $row) : ?>
<?php if(isset($records)) : foreach($records->result() as $row) : ?>
I have a weird problem with Codeigniter and Datamapper,
I am making an CMS system and I am trying to edit an article from the Database using Datamapper. When I click to edit the article I get the message 'You have succesfully saved the article ' without clicking on the SAVE button, also all the data becomes empty and leaves 0. When I enter the data and click on SAVE it saves it but again when I try edit it again it goes back to 0 ... Can someone help out please
Here is my edit function in the controller
public function edit($id = NULL)
{
// Get articles by ID
$articles = new Article_model();
$article = $articles->where('id', $id)->get();
if ($id)
{
$id == NULL || $article;
count($article) || $error = 'Page not found ';
}
else
{
$article = $this->article_model->get_new();
}
$article->title = $this->input->post('title');
$article->text = $this->input->post('text');
if ($article->save())
{
echo 'You have succesfully saved the article';
}
else
{
echo 'Sorry something went terribly worng';
}
$data = array(
'admin_content' => 'admin/article/edit',
'article' => $article,
);
$this->parser->parse('admin/template_admin', $data);
}
and here is my view
<?php if ($this->tank_auth->is_logged_in()): ?>
<div class="container">
<div class="row">
<div class="col-md-9">
<h3><?php echo empty($article->id) ? 'Add an article' : 'Edit a Page ' . $article->title ;?></h3>
<?php echo form_open(); ?>
<table class="table">
<tr>
<td>Publication Date</td>
<td><?php echo form_input('pubdate', set_value('pubdate', $article->pubdate), 'class="datepicker"'); ?></td>
</tr>
<tr>
<td>Title</td>
<td><?php echo form_input('title', set_value('title', $article->title)); ?></td>
</tr>
<tr>
<td>Body</td>
<td><?php echo form_textarea('text', set_value('text' , $article->text), 'class="tinymce"'); ?></td>
</tr>
<tr>
<td></td>
<td><?php echo form_submit('submit', 'Save', 'class="btn btn-primary"'); ?></td>
</tr>
</table>
<?php echo form_close(); ?>
</div>
</div>
</div>
<?php else: redirect('/auth/login'); ?>
<?php endif; ?>
that's not weird at all...every time that controller is loaded it's going to execute the save() method of the article class.
you should probably include some form validation and only save the article if the form was submitted and validation passes.