Adam J
Adam J

Reputation: 508

Codeigniter Pagination via Ajax / Jquery issue

So, I have a new CodeIgniter Project, and I'm working on displaying a collection of Fantasy Sports scores, grouped by week. I have the general consensus working if you click on each "week" individually, but the "Next Page" link doesn't work, and "Previous Page" doesn't show up as expected, and the "active page" does't switch either. Here is what I have so far:

DB Fiddle
https://www.db-fiddle.com/f/5Q7QezddpNEGabaia2w5FQ/0

VIEW

<div class="row">
    <div class="col-sm-12">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title">Scores</h4>
            </div>
            <div class="card-body">
                <div align="right" id="pagination_link"></div>
                <div class="table-responsive" id="week_table"></div>
            </div>
        </div>
    </div>
</div>
<script>
    var league_id = "1";

    function load_league_week_scores(week, league, page) {
            $.ajax({
                url:"<?php echo base_url();?>leagues/league_scores_pagination/"+week+"/"+league+"/"+page,
                method: "GET",
                dataType: "json",
                success: function(data)
                {
                    $('#week_table').html(data.week_table);
                    $('#pagination_link').html(data.pagination_link);
                }
            })
        }
    $(document).ready(function () {
        load_league_week_scores(1,league_id,1);
    });

    $(document).on("click", ".pagination li a", function(event) {
        event.preventDefault();
        var page = $(this).data("ci-pagination-page");
        load_league_week_scores(page, league_id, page);
    })
</script>

ROUTES

$route['leagues/league_scores_pagination/(:num)/(:num)/(:num)'] = "leagues/league_scores_pagination/$1/$2/$3";

CONTROLLER

<?php
if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Leagues extends CI_Controller
{
    private $league_id;


    function league_scores_pagination($week, $league, $page)
    {
        $this->load->model('Leagues_model', 'leagues_model');
        $this->load->library('pagination');
        $this->leagues_model->setLeagueId($league);

        $num_weeks = $this->leagues_model->GetGamesCount();
        $total_rows = $num_weeks * 5;
        //https://www.youtube.com/watch?v=nfDMTzmGi9Q
        $config = array();
        $config['base_url'] = "#";
        $config["total_rows"] = $total_rows;
        $config["per_page"] = 5;
        $config["uri_segment"] = 4; // I've made changes to this nothing has fixed it.
        $config['full_tag_open']    = '<div class="paging text-center"><nav><ul class="pagination">';
        $config['full_tag_close']   = '</ul></nav></div>';
        $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_tag_close']  = '<span aria-hidden="true"></span></span></li>';
        $config['prev_tag_open']    = '<li class="page-item"><span class="page-link">';
        $config['prev_tag_close']  = '</span></li>';
        $config['first_tag_open']   = '<li class="page-item"><span class="page-link">';
        $config['first_tag_close'] = '</span></li>';
        $config['last_tag_open']    = '<li class="page-item"><span class="page-link">';
        $config['last_tag_close']  = '</span></li>';
        $config["links"] = $num_weeks;
        $config["num_links"] = $num_weeks;
        $this->pagination->initialize($config);

        $output = array(
            'pagination_link' => $this->pagination->create_links(),
            'week_table' => $this->leagues_model->fetch_details($week)
        );

        echo json_encode($output);
    }
}

MODEL

<?php


class Leagues_model extends CI_Model
{
    private $league_id;

    public function __construct()
    {
        parent::__construct();
    }

    public function setLeagueId($league_id)
    {
        $this->league_id = $league_id;
    }

    public function GetGamesCount($league_id = "")
    {
        if (!empty($league_id)) {
            $this->league_id = $league_id;
        }

        // Get our league count
        $league_size = $this->GetLeagueSize();

        if (empty($league_size)) {
            return false;
        }

        $sql = "SELECT COUNT(nfl_user_matchups_id) as league_games FROM nfl_user_matchups WHERE leagues_id = ?";
        $query = $this->db->query($sql, $this->league_id);
        $count_leagues = $query->row()->league_games;
        $return_count = $count_leagues / $league_size;

        return $return_count;
    }

    public function GetLeagueSize()
    {
        if (empty($this->league_id)) {
            return false;
        }
        $sql = "SELECT max_capacity FROM leagues WHERE leagues_id = ?";
        $query = $this->db->query($sql, $this->league_id);

        return $query->row()->max_capacity;
    }

    public function fetch_details($week)
    {
        $output = "";
        $sql = "SELECT week, home_team_id, away_team_id, my_score, their_score, a.team_name as home_team, b.team_name as away_team 
                    FROM nfl_user_matchups nm 
                        LEFT JOIN user_teams a ON nm.home_team_id = a.user_teams_id 
                        LEFT JOIN user_teams b ON nm.away_team_id = b.user_teams_id 
                    WHERE nm.week = ? AND nm.leagues_id = ? 
                    GROUP BY Greatest(home_team_id, away_team_id), Least(home_team_id, away_team_id)";

        $query = $this->db->query($sql, array($week, $this->league_id));
        $output .= '<table class="table table-bordered">';
        foreach ($query->result() as $row) {
            if($row->my_score > $row->their_score) {
                $home_bold = 'style="font-weight: bold;"';
                $away_bold = '';
            } else {
                $away_bold = 'style="font-weight: bold;"';
                $home_bold = '';
            }
            $output .= '<tr><td ' . $home_bold . '>' . $row->home_team . '</td>';
            $output .= '<td>' . $row->my_score . '-' . $row->their_score . '</td>';
            $output .= '<td ' . $away_bold . '>' . $row->away_team . '</td></tr>';
        }
        $output .= '</table>';
        return $output;
    }
}

As I said, I'm getting the results as expected, but the pagination create_links() function is failing to populate properly. Here is a video that explains what is and is not working:

https://www.screencast.com/t/7eqyatyGV

Upvotes: 0

Views: 78

Answers (1)

Mohammedshafeek C S
Mohammedshafeek C S

Reputation: 1943

Things to update

  • Calculations you are doing in 'league_scores_pagination' are wrong. I passed total number of result as 5 (static and query returns that much ) and pagination is generating.
  • You aren't doing any pagination code in your modal too.
  • load_league_week_scores(week_id, league_id, page) -> you where passing 'page' twice
  • var week_id = 1; added by myself. You need to pass it to the controller by any of the method to make it dynamic

Updated Code

<script>
    var league_id = "1";
    var week_id = 1;

    function load_league_week_scores(week, league, page) {

            $.ajax({
                url:"<?php echo base_url();?>leagues/league_scores_pagination/"+week+"/"+league+"/"+page,
                method: "GET",
                dataType: "json",
                success: function(data)
                {
                    $('#week_table').html(data.week_table);
                    $('#pagination_link').html(data.pagination_link);
                }
            })
        }
    $(document).ready(function () {
        load_league_week_scores(week_id,league_id,1);
    });

    $(document).on("click", ".pagination li a", function(event) {
        event.preventDefault();
        var page = $(this).data("ci-pagination-page");
        load_league_week_scores(week_id, league_id, page);
    })
</script>


    function league_scores_pagination($week, $league, $page)
    {
        $per_page = 2;

        $this->load->model('Leagues_model', 'leagues_model');
        $this->load->library('pagination');
        $this->leagues_model->setLeagueId($league);

        $num_weeks = $this->leagues_model->GetGamesCount();
        $total_rows = 5;//$num_weeks * 5;
        //https://www.youtube.com/watch?v=nfDMTzmGi9Q
        $config = array();
        $config['base_url'] = "#";
        $config["total_rows"] = $total_rows;
        $config["per_page"] = $per_page;
        $config["uri_segment"] = 4; // I've made changes to this nothing has fixed it.
        $config['full_tag_open']    = '<div class="paging text-center"><nav><ul class="pagination">';
        $config['full_tag_close']   = '</ul></nav></div>';
        $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_tag_close']  = '<span aria-hidden="true"></span></span></li>';
        $config['prev_tag_open']    = '<li class="page-item"><span class="page-link">';
        $config['prev_tag_close']  = '</span></li>';
        $config['first_tag_open']   = '<li class="page-item"><span class="page-link">';
        $config['first_tag_close'] = '</span></li>';
        $config['last_tag_open']    = '<li class="page-item"><span class="page-link">';
        $config['last_tag_close']  = '</span></li>';
        $config['page_query_string'] = FALSE;
        $config['use_page_numbers'] = TRUE;
        // $config["links"] = $num_weeks;
        // $config["num_links"] = $num_weeks;
        $this->pagination->initialize($config);

        $output = array(
            'pagination_link' => $this->pagination->create_links(),
            'week_table' => $this->leagues_model->fetch_details($week,$page,$total_rows,$per_page)
        );

        echo json_encode($output);
    }

public function fetch_details($week, $page, $total_rows, $per_page = 10)
{

    $totalpages = ceil($total_rows / $per_page);

    if (isset($page) && is_numeric($page)) {
       $currentpage = (int) $page;
    } else {
       $currentpage = 1;
    }

    if ($currentpage > $totalpages) {           
       $currentpage = $totalpages;
    }

    if ($currentpage < 1) {
       $currentpage = 1;
    }

    $offset = ($currentpage - 1) * $per_page;


    $output = "";
    $sql = "SELECT week, home_team_id, away_team_id, my_score, their_score, a.team_name as home_team, b.team_name as away_team 
                FROM nfl_user_matchups nm 
                    LEFT JOIN user_teams a ON nm.home_team_id = a.user_teams_id 
                    LEFT JOIN user_teams b ON nm.away_team_id = b.user_teams_id 
                WHERE nm.week = ? AND nm.leagues_id = ? 
                GROUP BY Greatest(home_team_id, away_team_id), Least(home_team_id, away_team_id) LIMIT ?, ?";

    $query = $this->db->query($sql, array($week, $this->league_id, $offset, $per_page));
    $output .= '<table class="table table-bordered">';
    foreach ($query->result() as $row) {
        if($row->my_score > $row->their_score) {
            $home_bold = 'style="font-weight: bold;"';
            $away_bold = '';
        } else {
            $away_bold = 'style="font-weight: bold;"';
            $home_bold = '';
        }
        $output .= '<tr><td ' . $home_bold . '>' . $row->home_team . '</td>';
        $output .= '<td>' . $row->my_score . '-' . $row->their_score . '</td>';
        $output .= '<td ' . $away_bold . '>' . $row->away_team . '</td></tr>';
    }
    $output .= '</table>';
    return $output;
}

You can do a test by calling controller and change the input values here.

http://baseurl_here/leagues/league_scores_pagination/1/1/4

Upvotes: 1

Related Questions