0

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; ?>

1 Answers1

1

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>
Nasik Ahd
  • 778
  • 1
  • 9
  • 22
  • well I think Method 1 is might be good because I still have other searching inputs like price range and categories (checkboxes). Is that ok if my url will be that long? Like for example if I put value on all my search filters? ` products.php?page='.$next_id.'&search='.$keyword.'&category='.$category[0].'&category='.$category[1].'&minimum='.$minimum.'&maximum='.$maximum.' ` – Jack Calvin Sep 21 '20 at 06:55
  • There is a limit, but this is far from it. – Gabriel Alejandro López López Sep 21 '20 at 07:02
  • what do you mean there's a limit? on url and GET parameters? – Jack Calvin Sep 21 '20 at 07:08
  • @JackCalvin refer this https://stackoverflow.com/questions/7724270/max-size-of-url-parameters-in-get – Nasik Ahd Sep 21 '20 at 07:33
  • oh I see,, well I think i'm not gonna reach that much and also the limit is on every parameter right not specifically limited on query parameters like `?category[0]=1&category[1]=3&category[2]=19 ` – Jack Calvin Sep 21 '20 at 07:41
  • No it is for complete parameters, in case your sending a array of variable like above one **category[0]=1&category[1]=3&** by using a javascript function change like this **category=1,3,19** and proceed. – Nasik Ahd Sep 21 '20 at 08:50
  • is it possible? how? – Jack Calvin Sep 21 '20 at 09:40
  • wait I just remembered I can't implode that thing coz I have some categories that has two or more categories (e.g 1,2 -> one category) if I do that, unless it be category=[1,2],[3],[2,5] – Jack Calvin Sep 21 '20 at 13:17
  • @JackCalvin can you post your filter inputs? – Nasik Ahd Sep 22 '20 at 03:44
  • i've tried but everytime I go to next page (I've set my pagination to a GET method search.php?page=2), the POST values getting cleared – Jack Calvin Sep 22 '20 at 14:03