wrong current page on codeigniter pagination for ajax content - ajax

Content on one of my page is fetched through Ajax. Content and pagination are all processed and loaded into container div pretty well except for the challenge of wrong placement of CURRENT PAGE on the pagination.
1st page is always set as current page and I cant seem to figure out why
URL sample for e.g 2nd page:
http://localhost/mysite/index.php/category/item/2
Pagination method being called by Ajax:
Method is passed two POST param cat_id for content to fetched from DB and current page number
public function category_product_pagination(){
if(!empty($this->input->post('cat_id')) && !empty($this->input->post('page'))){
$cat_id_enc = $this->input->post('cat_id');
$cat_id = $this->decryptGetId($cat_id_enc);
$page = $this->input->post('page');
$slug = $this->ajax_model->dbSingleColQuery('slug', 'product_category', "id = '".$cat_id."'");
/////////////// PAGINATION //////////////
$config = array();
$config["base_url"] = base_url() . "/category/".$slug;
$total_row = $this->ajax_model->dbRowCountQuery('product', "cat_id = '".$cat_id."' AND del_status = 0");
$config["total_rows"] = $total_row;
$config["per_page"] = $this->per_page;
$config['use_page_numbers'] = TRUE;
$config['num_links'] = 2;
$config['next_link'] = 'Next';
$config['prev_link'] = 'Previous';
$config['uri_segment'] = 3;
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '</li>';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
$config['cur_tag_open'] = '<li><a class="current">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$this->pagination->initialize($config);
$limit_row = ($page == 1) ? 0: ($page - 1) * $config["per_page"];
$product_list = $this->ajax_model->dbMultiRowQuery('*', 'product', "cat_id = '".$cat_id."' AND del_status = 0", 'id', 'DESC', $limit_row, $config["per_page"]);
$str_links = $this->pagination->create_links();
$pagination = explode(' ',$str_links);
/////////////// PAGINATION //////////////
echo '<ul class="tsc_pagination">';
foreach ($pagination as $key => $link) {
echo $link;
}
echo '</ul>';
}
}// End function
Ajax/Jquery
(function($){
var cat_id = $("#filter_form_id input[name=cat_id]").val();
var form_data = {
cat_id : cat_id,
page : page,
secure_csrf_token_name : csrf
}
$("#this_category_product_container").html('<img src="'+base_url+'assets/img/ajax-loader.gif" />');
$.ajax({
url : site_url+"/category-product-loader",
type : "POST",
data : form_data,
dataType: "html",
cache : false
})
.done(function(resp){
if(resp == 5){
$("#this_category_product_container").html(respMsg('No product match found!', 2));
}
else{
$("#this_category_product_container").html(resp); // Product Loading into container tag
// Generate Pagination
$.ajax({
url: site_url+'/category-product-pagination',
type : "POST",
cache: false,
dataType: "html",
data : form_data,
success: function(paginate){
//alert(page);
$("#pagination").html(paginate);
}
});
// Generate Pagination
}
})
.fail(function(){
$("#this_category_product_container").html('Query to sever unsuccessful. Try again shortly!');
});
})(jQuery);
Would be pleased to get some help...

I think that the problem may be that you didn't declare the page variable in ajax.
(function($){
var cat_id = $("#filter_form_id input[name=cat_id]").val();
// where is var page??
var form_data = {
cat_id : cat_id,
page : page,
secure_csrf_token_name : csrf
}
...

Finally figured out the problem. Simply added
$config['cur_page'] = $page;
to the pagination config initialize and that passed the value of the current page to the Pagination class

Related

How to show continued numbered of data with pagination

I am trying to display data in an ordered list with pagination in codeigniter. The numbered works fine in first page number 1 until limit, but in the next page it counts down start to 1, not continuing from previous page.
here is the controller code :
public function index()
{
// init params
$params = array();
$limit_per_page = 2;
$start_index = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$total_records = $this->model_pesan->get_total();
$data['setting'] = $this->setting_model->get_file();
if ($total_records > 0)
{
// get current page records
$params["results"] = $this->model_pesan->get_current_page_records($limit_per_page, $start_index);
$params["ruangan"] = $this->ruangan_model->get_file();
$config['base_url'] = base_url() . 'home/index';
$config['total_rows'] = $total_records;
$config['per_page'] = $limit_per_page;
$config["uri_segment"] = 3;
$config['full_tag_open'] = '<nav><ul class="pagination justify-content-center">';
$config['full_tag_close'] = '</ul></nav>';
$config['num_tag_open'] = '<li class="page-item"><span class="page-link">';
$config['num_tag_close'] = '</span></li>';
$config['cur_tag_open'] = '<li class="page-item active"><span class="page-link">';
$config['cur_tag_close'] = '<span class="sr-only">(current)</span></span></li>';
$config['next_tag_open'] = '<li class="page-item"><span class="page-link">';
$config['next_tagl_close'] = '<span aria-hidden="true">»</span></span></li>';
$config['prev_tag_open'] = '<li class="page-item"><span class="page-link">';
$config['prev_tagl_close'] = '</span></li>';
$config['first_tag_open'] = '<li class="page-item"><span class="page-link">';
$config['first_tagl_close'] = '</span></li>';
$config['last_tag_open'] = '<li class="page-item"><span class="page-link">';
$config['last_tagl_close'] = '</span></li>';
$this->pagination->initialize($config);
// build paging links
$params["links"] = $this->pagination->create_links();
}
$this->load->view('template/header_user', $data);
$this->load->view('user/home', $params);
$this->load->view('template/footer_user', $data);
}
and this is the model code :
public function get_current_page_records($limit, $start)
{
$query = $this->db->query('set #row_number = 0');
$this->db->select('(#row_number:=#row_number + 1) as num ,reservasi.id_reservasi,DATE_FORMAT(reservasi.tanggal, "%d-%m-%Y") as tanggal, reservasi.acara, reservasi.waktu_mulai, reservasi.waktu_selesai, reservasi.keterangan, ruangan.nama_ruangan, user.nama, reservasi.organisasi, reservasi.notelp');
$this->db->from('reservasi');
$this->db->join('user', 'reservasi.id_user = user.id');
$this->db->join('ruangan', 'reservasi.id_ruangan = ruangan.id_ruangan');
$this->db->limit($limit, $start);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$data[] = $row;
}
return $data;
}
return false;
}
public function get_total()
{
return $this->db->count_all_results('reservasi');
}
the ouput should be =
first page :
1
2
3
4
then in the next page :
5
6
7
8
Try to set the row_number to $start+1 instead of 0 on the model, so it will not start from 0 again on every page requested :
$query = $this->db->query('set #row_number = '.$start+1);

Why do i get the same values in all pages in CI pagination?

I'm kinda new in CI and i'm trying to create a proper pagination for my page.
I have the following model and controller and even if i manage to get the pagination links, when i visit the other pages i get the same entries again and again.
I also have applied an Ajax "GET" filtering for fetching results from db and i managed to reuse the url parameters when i change pages.
The problem is that i don't know if i should try to create an infinite scroll function or maintain the default CI pagination.
I'd like to hear your opinions too!
Thank you in advance!
public function get_filtered_pets($limit, $start){
$this->db->order_by('pet_created_at', 'DESC');
$this->db->join('users', 'users.user_id = pets.pet_user_id');
$this->db->join('pet_categories', 'pet_categories.pet_category_id = pets.category_id');
$pet_data = array();
if ( $this->input->get('petStatus') ) {
$pet_data['pet_status'] = $this->input->get('petStatus');
}
if ( $this->input->get('petCategory') ) {
$pet_data['category_id'] = $this->input->get('petCategory');
}
if ( $this->input->get('petGender') ) {
$pet_data['pet_gender'] = $this->input->get('petGender');
}
if ( !empty($pet_data) ) {
$this->db->where($pet_data);
}
$query = $this->db->get('pets');
if ($start > 0) {
$this->db->last_query();
}
return $query->result_array();
}
And my controller
public function index(){
$query = $this->db->get('pets');
$pet_num = $query->num_rows();
$config = array();
$config["base_url"] = base_url() . "pets/index/";
$config["total_rows"] = $pet_num;
$config["per_page"] = 12;
$config['use_page_numbers'] = TRUE;
$config['reuse_query_string'] = TRUE;
$config['attributes'] = array('class' => 'page-link');
$config["full_tag_open"] = '<ul class="pagination">';
$config["full_tag_close"] = '</ul>';
$config["first_link"] = "«";
$config["first_tag_open"] = "<li>";
$config["first_tag_close"] = "</li>";
$config["last_link"] = "»";
$config["last_tag_open"] = "<li>";
$config["last_tag_close"] = "</li>";
$config['next_link'] = '>';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '<li>';
$config['prev_link'] = '<';
$config['prev_tag_open'] = '<li class="page-item">';
$config['prev_tag_close'] = '<li>';
$config['cur_tag_open'] = '<li class="page-item active"><a class="page-link" href="#">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data['pets'] = $this->pet_model->get_filtered_pets($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
//View files
$this->load->view('templates/header', $data);
$this->load->view('pets/index', $data);
$this->load->view('templates/footer', $data);
}
You are not using the value of $limit and $start nowhere. See Limiting or Counting Results.
You should:
public function get_filtered_pets($limit, $start){
$this->db->limit($limit, $start);
/* ... */
return $query->result_array();
}
And also, when calling this function you have to multiply: per_page * page, to get the offset (starting index).
$this->pet_model->get_filtered_pets($config["per_page"], $page * $config["per_page"])
To count results correctly, I normally have two functions on model: "get($search, $offset)" and "count($search)".
The function count has exactly the same code on get, except the select fields.
See this code, I think you will get it: https://pastebin.com/dZG90Lzm.
ps: There's ways to optimize it and avoid duplicate code.

Pagination on Codeigniter

//Controller
function search($search = 0)
{
$this->form_validation->set_rules("search", "Search", "trim|required|xss_clean");
$searchemp = $this->input->post('search');
$data['result'] = $this->main_model->search_employee($searchemp);
$data['resultcount'] = count($this->main_model->search_employee($searchemp));
//$result = $this->main_model->search_employee($searchemp);
//$this->display($this->main_model->search_employee($searchemp));
$config['base_url'] = base_url().'main/search';
$config['anchor_class'] = 'test';
$config['total_rows'] = $data['resultcount'];
$config['per_page'] = 10;
$config['num_links'] = 5;
$config['use_page_numbers'] = TRUE;
$config['full_tag_open'] = '<ul class="pagination">';
$config['full_tag_close'] = '</ul>';
$config['prev_link'] = '«';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '</li>';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
$config['cur_tag_open'] = '<li class="active"><a href="#">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['next_link'] = '»';
$this->pagination->initialize($config);
$tmpl = array ( 'table_open' => '<table class="table table-bordered table-hover">' );
$this->table->set_template($tmpl);
//$data['searchresult']=$this->db->get($result, $config['per_page'],$search);// take record of the table
$header = array('Employee Number','Name'); // create table header
$this->table->set_heading($header);// apply a heading with a header that was created
$this->load->view('results_view',$data);
}
//Model
function search_employee($searchemployee)
{
$sql = "select Empcode, Name from spmm_employee_info where name like '%" . $searchemployee . "%'";
$query = $this->db->query($sql);
return $query->result_array();
}
When i try to search and click on the other page, it displays all the data on the table spmm_employee_info. All i want is to display all the results related to the search and not all data when i click the page on the pagination. Please help
Use mysql DATE_FORMAT and convert date time in time Like this demo query
SELECT DATE_FORMAT(colName,'%H:%i:%s') TIMEONLY from tbl where TIMEONLY='7:01AM'

code igniter pagination for displaying specific data from database?

I want to display some specific data from database through pagination using CI.but pagination by default passess parameter in function which creates problem for me.
Here is my Controller
function page($catagoryid){
$this->load->library('pagination');
$config['base_url'] = base_url().'index.php/pagination/page/';
$count = $this->db->query("select * from tbl_products where category_id='$categoryid'");
$total=$count->num_rows();
$per_page = 4;
$config['total_rows'] = $total;
$config['per_page'] = $per_page;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$this->load->model("mpagination");
$data['list'] = $this->mpagination->get_s(,$categoryid,$config['per_page'],$this->uri->segment(3));
if ($data['list']!== null){
$this->load->view('pagination_view', $data);
}
else {
$this->load->view('noresult');
}
}
Here is my Model
function get_s($categoryid,$num, $offset) {
$this->db->select ('*');
->where('category_id',$categoryid); // field name
$sql = $this->db->get('tbl_products',$num, $offset); // table name
if ($sql->num_rows () >0) {
return $sql->result();
}
else {
return null;
}
}
Here is my view
<?php
foreach($list as $row):?>
<?php echo $row->_prduct_id." ".$row->name." ".$row->description;?>
<br/>
<?php endforeach;?>
<br/>
<?php echo $pagination; ?>
This code work at first but when i clicked on second link of pagination it will not work because by default pagination sends its value to url as parameter and doesnot show data.
what can i do?
I didn't understand your code properly but this is the way you need to do pagination.
public function page($category_id)
{
$result = $this->model_file->model_function($category_id);
$start_index = 0;
$total_rows = count($result);
$items_per_page = 10;
$filtered = array_splice($result,$start_index,$items_per_page);
$model['data'] = $filtered;
$model['page_link'] = create_page_links (base_url()."/controller_file_name/page", $items_per_page, $total_rows);
$this->load->view('view_file_name_path',$model);
}
function create_page_links($base_url, $per_page, $total_rows) {
$CI = & get_instance();
$CI->load->library('pagination');
$config['base_url'] = $base_url;
$config['total_rows'] = $total_rows;
$config['per_page'] = $per_page;
$CI->pagination->initialize($config);
return $CI->pagination->create_links();
}
Try like this
public function index($offset = 0)
{
$language_id = 1;
$this->load->library('pagination');
$limit = 10;
$total = $this->legend_model->get_legend_count($language_id);
$config['base_url'] = base_url().'legend/index/';
$config['total_rows'] = $total;
$config['per_page'] = $limit;
$config['uri_segment'] = 3;
$config['first_link'] = '<< First';
$config['last_link'] = 'Last >>';
$config['next_link'] = 'Next ' . '>';
$config['prev_link'] = '<' . ' Previous';
$config['num_tag_open'] = '<span class="number">';
$config['num_tag_close'] = '</span>';
$config['cur_tag_open'] = '<span class="current"><a href="#">';
$config['cur_tag_close'] = '</a></span>';
$this->pagination->initialize($config);
$data['offset'] = $offset;
$data['legends'] = $this->legend_model->get_legend($language_id, $limit, $offset);
$this->template->write('title', 'Legend : Manage Legend');
$this->template->write_view('content', 'legend/index', $data);
$this->template->render();
}

code igniter pagination with sort options

I'm not sure if what I'm about to ask is possible or not.. I'm thinking probably not but I thought I would ask anyways.
Is there any way to reset the pagination?
I've got a page with has pagination and sort option on it. Everything works fine but when one of the sort options is changed I would like to send the user back to the first page.
(I'm pretty sure the way I'm doing this isn't at all the best way to get the result I want so if you have any suggestions for improvements please feel free.)
$array = explode ("_",$this->uri->segment(4));
if(count($array) > 1){
$search_id = $array[1];
$start = $this->uri->segment(5);
$uri_segment = 5;
}else{
$start = $this->uri->segment(4);
$uri_segment = 4;
$search_id = null;
}
$config['per_page'] = $this->settings['PRODUCTS_PER_PAGE'];
$config['total_rows'] = $this->categories_model->get_num_rows($cat_id , $search_type, $search_data);
$query = $this->categories_model->get_category_pages($cat_id, $new_limit, $new_sort, $search_id, $start, $this->settings['CATEGORY_ORDER'], $search_type, $search_data, $config['total_rows']))
$config['base_url'] = base_url() . 'index.php/categories/view/' . $cat_id ."/" . $search_string ;
$config['uri_segment'] = $uri_segment;
//Congig settings for pagination
$config['full_tag_open'] = '<div id="pagination" style= "clear:both;">';
$config['full_tag_close'] = '</div>';
//Initialise pagination
$this->pagination->initialize($config);
you may keep a default sorting in controller which will not show in url.so sorting will not back to the first page.
a sample
class Post extends Jewelery_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Prime_model');
}
public function index($ordr_by = 'post_title', $sortr = 'ASC') {
if ($this->uri->segment(6)) {
$data['segment'] = $this->uri->segment(6);
} else {
$data['segment'] = 0;
}
if ($this->uri->segment(4)) {
$ordr_by = $this->uri->segment(4);
}
if ($this->uri->segment(5)) {
$sortr = $this->uri->segment(5);
}
$data['title'] = 'All Posts';
$this->load->library('pagination');
$config['base_url'] = base_url() . 'admin/post/index/' . $ordr_by . '/' . $sortr;
$config['full_tag_open'] = '<div class="pagination"><ul>';
$config['full_tag_close'] = '</ul></div>';
$config['cur_tag_open'] = '<li class="active"><a href="">';
$config['cur_tag_close'] = '</a></li>';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '</li>';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['uri_segment'] = 6;
$config['total_rows'] = $this->db->get('jewel_posts')->num_rows();
$config['per_page'] = 10;
$this->pagination->initialize($config);
$data['post_info'] = $this->Prime_model->master_join('jewel_posts', 'jewel_jewelry_type', 'jewel_posts.jewelry_type = jewel_jewelry_type.jewelry_type_id', 'left', FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, $ordr_by, $sortr, $config['per_page'], $data['segment']);
$this->load->view('admin/header', $data);
$this->load->view('admin/post/index');
$this->load->view('admin/footer');
}

Resources