Jack Calvin
Jack Calvin

Reputation: 1

PHP - Search with Pagination

So I have these two PHP files products.php and receive.php .
What my problem is I want to use Ajax on displaying the products with search and paginates also. The code below works though but only if I use a GET.
Is it possible to submit only the page number and refreshes only the div (where products loop) and not the whole page so that my POST requests (from search values - title, keywords) will still hold? coz if I use GET on pagination, the POST requests are getting empty after clicking the second page.

receive.php

$pdo_sql = 'SELECT * FROM items WHERE item_title LIKE %$keyword% OR keywords LIKE %$keyword% ORDER BY id DESC ';

/*** Pagination Code starts ***/
$per_page_html = '';
$page = 1;
$start=0;

// Get Page Number
if(!empty($_GET["page"])) {
    $page = $_GET["page"];
    $start=($page-1) * ROW_PER_PAGE;
}
// Adds Limit to Query then Execute
$limit=" LIMIT " . $start . "," . ROW_PER_PAGE;
$pagination_statement = $pdo_conn->prepare($pdo_sql);
$pagination_statement->bindValue(':keyword', '%' . $keyword . '%', PDO::PARAM_STR);
$pagination_statement->execute();
// Count the total number of rows  
$row_count = $pagination_statement->rowCount();
if(!empty($row_count)){
    
    $total_links=ceil($row_count/ROW_PER_PAGE);
    $previous_link = $next_link = $page_link = '';

    if($total_links > 4)
    {
      if($page < 5)
      {
        for($count = 1; $count <= 5; $count++)
        {
          $page_array[] = $count;
        }
        $page_array[] = '...';
        $page_array[] = $total_links;
      }
      else
      {
        $end_limit = $total_links - 5;
        if($page > $end_limit)
        {
          $page_array[] = 1;
          $page_array[] = '...';
          for($count = $end_limit; $count <= $total_links; $count++)
          {
            $page_array[] = $count;
          }
        }
        else
        {
          $page_array[] = 1;
          $page_array[] = '...';
          for($count = $page - 1; $count <= $page + 1; $count++)
          {
            $page_array[] = $count;
          }
          $page_array[] = '...';
          $page_array[] = $total_links;
        }
      }
    }
    else
    {
      for($count = 1; $count <= $total_links; $count++)
      {
        $page_array[] = $count;
      }
    }
    
    for($count = 0; $count < count($page_array); $count++)
    {
      if($page == $page_array[$count])
      {
            // Current Page = Selected Page
        $page_link .= '<a class="paginate_current" href="javascript:void(0)">'.$page_array[$count].'</a>';
    
        $previous_id = $page_array[$count] - 1;
        if($previous_id > 0)
        {
            // Previous Button Enable 
            $previous_link = '<a class="paginate_prev" href="products.php?page='.$previous_id.'">Previous</a>';
        }
        else
        {
            // Previous Button Disabled 
            $previous_link = '<a class="paginate_prev-disabled" href="javascript:void(0)">Previous</a>';
        }
        $next_id = $page_array[$count] + 1;
        if($next_id > $total_links)
        {
            // Next Button Disabled
            $next_link = '<a class="paginate_next-disabled" href="javascript:void(0)">Next</a>';
        }
        else
        {
            // Next Button Enabled

                $next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'">Next</a>';
        }
      }
      else
      {
        if($page_array[$count] == '...')
        {
            // Ellipsis 
            $page_link .= '<a class="paginate_ellipsis" href="javascript:void(0)">...</a>';
        }
        else
        {
            // Pages 
             $page_link .= '<a class="paginate_pages" href="products.php?page='.$page_array[$count].'">'.$page_array[$count].'</a>';
        }
      }
    }
    
    $per_page_html .= '<div class="text-center paginate">';
    $per_page_html .= $previous_link . $page_link . $next_link;
    $per_page_html .= '</div>';

}

$query = $pdo_sql.$limit;
$pdo_statement = $pdo_conn->prepare($query);
$pdo_statement->bindValue(':keyword', '%' . $keyword . '%', PDO::PARAM_STR);
$pdo_statement->execute();
$pdo_result = $pdo_statement->fetchAll();

products.php

            <div class="row">
                <div class="col">
                    <div class="products_container grid" id="refresh">
                        <?php
                        if(!empty($pdo_result)) { 
                            foreach($pdo_result as $pdo_row) {

                                $id = $pdo_row['id'];
                                $name = $pdo_row['item_title'];
                                $img = $pdo_row['item_img'];
                                $price = $pdo_row['item_price'];
                                $sold = $pdo_row['item_sold'];
                                $stocks = $pdo_row['stocks'];
                                $date = $pdo_row['date'];

                                if ($sold >= $max && $date != date("Y-m-d") ) {
                                    $sort = 'hot';
                                }else if($date == date("Y-m-d") && $sold <= $max){
                                    $sort = 'new';
                                }else{
                                    $sort = '';
                                }
                                echo '
                                <div class="product grid-item '.$sort.'">
                                    <div class="product_inner">
                                        <div class="product_image">
                                            <a href="item.php?prod='.$id.' "><img src="'.$img.'" alt=""></a>
                                            <div class="product_tag">'.$sort.'</div>
                                        </div>
                                        <div class="product_content text-center">
                                            <div class="product_title text-long"><a href="item.php?prod='.$id.' ">'.$name.'</a></div>
                                            <div class="product_price">₱'.number_format($price).'</div>
                                            <div class="product_button ml-auto mr-auto trans_200">
                                                <button class="product_button ml-auto mr-auto trans_200" id="add2c" data-prod=" '.$id.' " type="button" >add to cart</button> 
                                            </div>
                                        </div>
                                    </div>  
                                </div>
                                ';
                            } //End Foreach Loop
                        }
                        else{
                            echo "no products found";
                        }
                    ?>
                    </div>
                </div>
            </div>
            <!-- PAGINATION HERE -->
            <?php echo $per_page_html; ?>

Upvotes: 0

Views: 573

Answers (1)

Nasik Ahd
Nasik Ahd

Reputation: 798

Method 1 => Without ajax

You can use the GET method for search value also. and in every pagination link append the search value too.
for example.

$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'">Next</a>';
        

instead of above line use below one.

$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'&search='.$keyword.'">Next</a>';


Method 2 => using ajax
instead of href use a javascript function like below

$next_link = '<a class="paginate_next" href="#" onclick="paginate_fn(\''.$next_id.'\', \''.$keyword.'\'">Next</a>'


<script>
  function paginate_fn(pageID, keyword){
        $.ajax({
            async: true,
            type: 'get', // you can use post also 
            dataType:'json',
            data: {'pageID':pageID, 'keyword': keyword},
            url: "paget_name.php", // your page name            
            success: function (data) {
                $('#search-content').html( data['content'] );
            },
            error: function () {
                alert('An Error Occurred!.');
            }
        });
    }
</script>

Upvotes: 1

Related Questions