<?php
 
class Site extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
 
        $this->load->library('pagination');
        $this->load->helper('url');
    }
 
    function index()
    {
        $this->load->view('site');
    }
 
    function search()
    {
        // could also store the below constant in config.php and load through
        // $this->load->config('site');
        // $this->config->item('PAGINATION_PER_PAGE')
        $per_page = 5;
 
        $search_terms = $this->input->post('search_terms');
        if (FALSE === $search_terms) {
            $search_terms = '';
        } else {
            $search_terms = trim($search_terms);
        }
 
        $offset = $this->input->post('offset');
        if (!($offset > 0)) {
            $offset = 0;
        }
 
        // query for search terms
        $items = new Item();
        $items->search($search_terms)
              ->get_paged($offset, $per_page, TRUE);
 
        // In case manual intervention on GET parameter segment gives an offset outside range.
        if ($offset > $items->paged->total_rows) {
            $offset = floor($items->paged->total_rows / $per_page) * $per_page;
        }
 
        $pagination_config = array(
            'base_url' => site_url('site/search'),
            'total_rows' => $items->paged->total_rows,
            'per_page' => $per_page,
            'uri_segment' => 3
        );
        $this->pagination->initialize($pagination_config);
 
        $data = array(
            'pagination' => $this->pagination,
            'search_terms' => $search_terms,
            'items' => $items,
            'offset' => $offset,
            /*
            DataMapper Pagination with AJAX

            Want to use AJAX to refresh paginated results inline? Instead of page links triggering a vanilla POST form request, they’ll invoke AJAX through POST. For the sake of brievity, I’ll make the AJAX request return HTML rather than dealing with JSON and client-side templating. Keep in mind DataMapper does offer easy to_json() and all_to_json() methods that could be used on the $items result. And Apache Solr I mentioned earlier? It also returns JSON.

            In our controller’s search() method, we’ll modify variables passed to the view template to include a boolean on whether the current request is by AJAX. This flag allows pagination links to behave differently.
            */
            'is_ajax_request' => $this->input->is_ajax_request()
        );
 
        $this->load->view('search_results', $data);
    }
}


?>