1
\$\begingroup\$

This is the first time that I have add (I mean, I try) Ajax with Jquery to PHP and Mysql (pagination). This is a link to the test page: testpage1

I think everything works, but is it done correctly?

Thank you in advance for good advice .

1. Ajax(index.php)

$(window).on('load', function () { // makes sure that whole site is loaded
    $('#status').fadeOut();
    $('#preloader').delay(350).fadeOut('slow');
});

                
 $(document).ready(function(){  
            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);
     // load_data(1);  
      function load_data(page)  
      {          
        $('#load_data').html('<div id="status" style="" ></div>');
        $.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}`)
            //window.history.pushState({page}, `Selected: ${page}`, `./selected=${page}`)
            return event.preventDefault(); 
       });
            window.addEventListener('popstate', e => {
            var page = $(this).attr("id");
            load_data(e.state.page);
            console.log('popstate error!');
    });
 }); 

2. pagination2.php

 <?php 
//$page = ''; 

$rowperpage = 10;
//$page = $_POST['page'] ?? 1;
$page = 1;
if($_POST['page'] > 1)
{
  $p = (($_POST['page'] - 1) * $rowperpage);
  $page = $_POST['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>Nie ma produktow w tej kategorii</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($_POST['page'] > 1)
    { 
      $page_nb = $_POST['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 "<a href=\"{$url}?page=" . $i . "\">{$i}</a>";
            //echo "<span class='pagination_link' style='cursor:pointer;' id='".$i."' onclick='window.history.go(1); return false;'>".$i."</span>"; 
            echo "<span class='pagination_link' style='cursor:pointer;' id='".$i."'>".$i."</span>"; 
            //echo "<a class='pagination_link' href='' id='".$i."'>{$i}</a>";
        }
      }
    }       
    
if ($products_count > $check) { 

$next_page = $page_nb + 1;  
    //echo "<a href='index_all.php?page=".$next_page."'>Next</a>";
    echo "<span class='pagination_link' style='cursor:pointer;' id='".$next_page."'>Next</span>";
    
}
    
?>

3. htaccess

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
\$\endgroup\$
6
  • \$\begingroup\$ If your code is not working as intended, you do not have an on-topic question. Broken coding attempts are appropriately posted on Stackoverflow. \$\endgroup\$ May 31 '19 at 11:33
  • \$\begingroup\$ The problem is that I have no experience with Ajax and Jquery and I do not know if it should work or not. \$\endgroup\$ May 31 '19 at 11:39
  • \$\begingroup\$ Quote from your question: "One thing I can not solve - once the user clicks the link 5 and go to product detail, when he comes back, he back to 1 not 5. I do not know why." This is why you should post on SO instead of CodeReview. We don't fix broken code, we refine working code here. \$\endgroup\$ May 31 '19 at 11:40
  • \$\begingroup\$ And ... it comes out that there is no error in the code, but it should be added "Jquery ajax to display product detail" . Today I found out about it but I still do not know how to do it :). \$\endgroup\$ May 31 '19 at 11:49
  • \$\begingroup\$ We also expect the author of the code to know what the code does and why. I'm sorry but your question is still off-topic. \$\endgroup\$
    – Summer
    May 31 '19 at 15:53