Skip to content
Advertisement

AJAX pagination, update current page

I created a numeric pagination that loads the data via AJAX.

This is the code:

 $(document).ready(function(){  
      load_data(1); 
     
      function load_data(page)  
      {          
        $.ajax({
                url:"pagination2.php",  
                method:"POST", 
                data:{page:page},  
                success:function(data){  
                     $('#load_data').html(data);
                } 
           }); 
      }  

      $(document).on('click', '.pagination_link', function(event) 
        {
            event.preventDefault(); 
            var page = $(this).attr("id"); 
            load_data(page);
            //Now push PAGE to URL
            window.history.pushState({page}, `Selected: ${page}`, `${'page=' +  page}`)
            return event.preventDefault(); 
      });
            window.addEventListener('popstate', e => {
            var page = $(this).attr("id");
            load_data(e.state.page);
            console.log('popstate error!');
    });
    
 }); 

The code works, but when I refresh the page the data are loaded again from the first page. test_ajax

Ex: If I click the button that loads the page 2 when I refresh the page the data are displayed from the page 1.

There is a way to remain on the same page even after the page refresh?

pagination2.php

<?php 

$rowperpage = 10;

$page = 1;
if($_REQUEST['page'] > 1)
{
  $p = (($_REQUEST['page'] - 1) * $rowperpage);
  $page = $_REQUEST['page'];
}
else
{
  $p = 0;
}

?>


<?php   
 $visible = $visible ?? true;
  
$products_count = count_all_products(['visible' => $visible]);    
      
$sql = "SELECT * FROM products ";
$sql .= "WHERE visible = true ";
$sql .= "ORDER BY position ASC ";
$sql .= "LIMIT ".$p.", ".$rowperpage."";  
        
$product_set = find_by_sql($sql);
      
$product_count = mysqli_num_rows($product_set);
    
if($product_count == 0) {
      echo "<h1>No products</h1>";
      }

while($run_product_set = mysqli_fetch_assoc($product_set)) { ?>

    <div style="float: left; margin-left: 20px; margin-top: 10px; class="small">

      <a href="<?php echo url_for('/show.php?id=' . h(u($run_product_set['id'])));   ?>">
          <img src="staff/images/<?php echo h($run_product_set['filename']); ?> " width="150">
        </a>

      <p><?php echo h($run_product_set['prod_name']); ?></p>

    </div>

    <?php }

    mysqli_free_result($product_set);
      
?>
<section id="pagination">
                           
    
<?php
    
$url = url_for('index_all.php');
                        
if($_REQUEST['page'] > 1)
    { 
      $page_nb = $_REQUEST['page'];
    }
    else
    {
      $page_nb = 1;
    }                       
                            
$check = $p + $rowperpage;
$prev_page = $page_nb - 1;

$limit = $products_count / $rowperpage;
    //echo $limit;
    //exit;
$limit = ceil($limit);
$current_page = $page_nb;
    
if($page_nb > 1) {
    //echo "<a href='index_all.php?page=".$prev_page."'>Back</a>";
    echo "<span class='pagination_link' style='cursor:pointer;'  id='".$prev_page."'>Back</span>";

}
    
if ( $products_count > $check ) {

    for ( $i = max( 1, $page_nb - 5 ); $i <= min( $page_nb + 5, $limit ); $i++ ) {
        if ( $current_page == $i ) {
            echo "<span class="selected">{$i}</span>";
        } else {
            echo "<span class='pagination_link' style='cursor:pointer;' id='".$i."'>".$i."</span>"; 
        }
      }
    }       
    
if ($products_count > $check) { 
$next_page = $page_nb + 1;  
    echo "<span class='pagination_link' style='cursor:pointer;' id='".$next_page."'>Next</span>";
    
}

Advertisement

Answer

When the document is ready you use load_data(1);

That’s wrong because if someone refreshes at page 5 it starts anyway from page 1.
Check the current page everytime you refresh. The code should be something like this:

var url_string = window.location.href;
var url_parts = url_string.split('/');
var piece = url_parts[url_parts.length -1]; //get last part of url (it should be page=n)
var page;
if(piece.substring(0, 5) === 'page=') {
   page = parseInt(piece.substr(5));
} else { //if it's the first time you landed in the page you haven't page=n
   page = 1;
}
load_data(page);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement