Automatically load content when you reach the bottom of the page

Asked

Viewed 16,157 times

8

I want to make an automatic page like Facebook, which when it reaches the bottom of the page automatically loads another page with more posts. I’ve already researched the subject and I haven’t found anything that could really help me to the point where I can.

The code I use to list posts is this:

<?php 
  $post = $pdo->query("SELECT * FROM postagens")->fetchAll();
if(!$post){
  print_r($pdo->errorInfo());
} 
foreach ($post as $posts){
?>

I tried to do what @abfurlan said and apparently I did something wrong.

The page index.php was like this:

<?php require_once"../conexao.php"?>

<style>
#conteudo{
width:100px; background:#CCC;
height:200px;
overflow-y:auto;
}
</style>

<script src="JS/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
  $("#conteudo").scroll(function() { 
    if ($(this).scrollTop() + $(this).height() == $(this).get(0).scrollHeight) {
      //requisição ajax para selecionar postagens
      $.ajax({
       url:'postagens.php', //Página PHP que seleciona postagens
       type:'POST', // método post, GET ...
       data: 'limit=5&offset=0', //seus paramêtros
       success: function(data){ // sucesso de retorno executar função
         $('#conteudo').append(data); // adiciona o resultado na div #conteudo
       } // fim success
    }); // fim ajax
  } // fim do if
}); // fim scroll
}); // fim document ready
</script>

<div id="conteudo">
</div>

And the page postagens.php was like this:

<?php require_once "../conexao.php" ?>

<?php 
$post = $pdo->query("SELECT * FROM postagens LIMIT 5 OFFSET 0")->fetchAll();
if(!$post){
    print_r($pdo->errorInfo());
} 
foreach ($post as $posts){
?>

<?php echo $posts['ID']; echo "<br>"?>

<?php } ?>

Nothing is going on...

  • 3

    I think the question does not sit well in "automatic page", I suggest changing the title to "load content according to scroll" or something like that

  • See if this post is useful, I believe this is what you are looking for: How to load content on demand using jQuery

3 answers

9


The technique you seek is called content on demand or infinite scroll.

Say you have in your code a div that carries its contents

<div id="conteudo">
    <p>Lorem Ipsum</p>
    <p>Lorem Ipsum</p>
    <p>Lorem Ipsum</p>
    <p>Lorem Ipsum</p>
    <p>Lorem Ipsum</p>
    <p>Lorem Ipsum</p>
</div>

And this div has a fixed height and overflow-y:scroll:

#conteudo{
    height:200px;
    overflow-y:auto;
}

Then you implement a jQuery code, for whenever the scroll reaches the end of the div, an ajax request is made to select more posts:

$(document).ready(function() {
    $("#conteudo").scroll(function() { 
      if ($(this).scrollTop() + $(this).height() == $(this).get(0).scrollHeight) {
        //requisição ajax para selecionar postagens
        $.ajax({
           url:'minha_pagina_acesso_banco.php', //Página PHP que seleciona postagens
           type:'POST', // método post, GET ...
           data: 'limit=10&offset=0', //seus paramêtros
           success: function(data){ // sucesso de retorno executar função
             $('#conteudo').append(data); // adiciona o resultado na div #conteudo
           } // fim success
        }); // fim ajax
      } // fim do if
    }); // fim scroll
}); // fim document ready

In your code that selects the posts you can make a LIMIT, OFFSET

SELECT * FROM postagens LIMIT 10 OFFSET 0 ORDER BY DESC;

On your PHP page, handle the parameters received by ajax to perform the query

<?php 
$sql = "SELECT * FROM postagens LIMIT ? OFFSET ?";
$stm = $pdo->prepare($sql);
$stm->execute(array($_POST['limit'],$_POST['offset']));
$post = $stm->fetchAll(PDO::FETCH_ASSOC);

if(!$post){
    print_r($pdo->errorInfo());
} 
foreach ($post as $posts){
    echo $posts['ID']; echo "<br>";
} ?>

And as per the scroll you increment these values in the ajax request to select more posts.

Here’s a simple example of jQuery code

  • I tried to do what you said and again I could not.

  • @ivanveloso edit the question to add the codes, so it is easier to understand

  • 1

    Edited question

  • @ivanveloso I edited the reply, you need to dynamically select the posts, in your case you are selecting all the posts at once.

  • 1

    gave this error /// Fatal error: Call to a Member Function fetchAll() on a non-object in C: wamp www calient jazz postagens.php on line 8 ////

  • @ivanveloso This error occurs when the query returns error, check your query, if the parameters are arriving correctly from $_POST.

  • The problem is that I am a sadness with php and jquery so in 50% of cases, even if it is a silly mistake I still can’t identify the problem

  • You can pass the data to the page or php will have to print with html/css?

Show 4 more comments

2

$(document).ready(function(){
    $(document).scroll(function() {

        var bottomDiv = $('#div-alvo').height() + $('#div-alvo').offset().top;
        var bottomWindow = $(window).height() + $(window).scrollTop());

        if (bottomWindow > bottomDiv ) {

            //Requisição


        } // fim do if
    }); // fim scroll
});

bottomDiv is the position in pixels from where the target div ends. bottomWindow is the bottom of the user screen.

When the bottom of the user screen exceeds the bottom of the target div, a new request must be made.

I hope I’ve helped.

-1

10

Document.getElementById("bcen").style.align = "center"; // Center Document.getElementById("bcen").style.width = "300px"; //Size Document.getElementById("bcen").style.align = "center"; // Center Document.getElementById("bcen").style.height = "200px"; //Size

Browser other questions tagged

You are not signed in. Login or sign up in order to post.