Click load more and increase LIMIT

1

I want to make a query for when I click the load more button, the LIMIT increases to display another 9 images in my gallery My Code:

<!-- connect.php -->
<?php
$host = "localhost";
$user = "root";
$db = "fenix";
$pass = "";

try{
    $connect = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
}catch(PDOException $e){
    die("Error ".$e->getMessage());
}

<!-- index.php -->
<?php
    require_once("connect.php");
?>

<script type="text/javascript"> 
$(document).ready(function(){
    $("#carregar_mais").click(function(){
        <?php $limite = $limite + 9;?>
    });
});
</script>

<?php
    $results = $connect->query("SELECT * FROM arquivo ORDER BY id_arquivo DESC LIMIT $limite");
?>

<div class="imagens">
    <?php   
        while($row = $results->fetch(){     ?>
            <a href="upload/uploads/<?php echo $row['nome_arquivo'];?>" > 
                <img class="imagem" src="upload/uploads/<?php echo $row['nome_arquivo'];?>" />
            </a>                                    
    <?php } ?>                       
</div>

<center>
    <p id="carregar_mais" style="color:white; cursor:pointer;">Carregar mais</p>
    <?php echo $limite;?> <!-- Este echo é só para exibir em quanto está meu LIMIT-->
</center>

When loading the page, 9 images appear. When I click "load more" should appear another 9 (18). It's like an infinite scroll, but the user decides when to load more images.

Thank you!

    
asked by anonymous 31.07.2016 / 20:16

1 answer

1

You're messing with JavaScript binding with PHP. JavaScript runs on the browser side and PHP runs on the server side.

Your limit only increases on the server side. You can through javascript make a new request to the server with 9 more.

Also fix your connection to DB. You are making confusion between mysqli and PDO.

<!-- index.php -->
 <?php
         require_once("connect.php");
         //recebe input do ?limite no URL
$limite = (isset($_GET['limite'])) ? $_GET['limite'] : 9;
?>
<script type="text/javascript">
$(document).ready(function(){
   $("#carregar_mais").click(function(){
       //novo pedido ao servidor com +9
       window.location.href = '/index.php?limite=<?php echo $limite+9;?>';
   });
});
</script>
<?php
   $sql = "SELECT * FROM arquivo ORDER BY id_arquivo DESC LIMIT $limite";
   $data = $connect->prepare($sql);
   $data->execute();
?>

<div class="imagens">
<?php
   $results = $data->fetchAll(PDO::FETCH_OBJ);
   foreach($results as $image)
     {
?>
     <a href="upload/uploads/<?php echo $image->nome_arquivo; ?>" >
        <img class="imagem" src="upload/uploads/<?php echo $image->nome_arquivo; ?>" />
   </a>
<?php } ?>
</div>

<center>
   <p id="carregar_mais" style="color:white; cursor:pointer;">Carregar mais</p>
   <?php echo $limite;?> <!-- Este echo é só para exibir em quanto está meu LIMIT-->
</center>

Alternatively you can use AJAX to make a request to the server without refreshing the page.

    
31.07.2016 / 20:37