store automatic pagination

0

This page is working perfectly, there is only one thing, when the person dece to the end it brings the last record of the bank everything right, there it is showing the message of Carregando... even having nothing else to display, like Could you sort it out? another thing, when scrolling up again hide the results of the displayed bank with scroll rolled down

HTML

<div id="posts">                
</div>            
<h1 id="carregando">Carregando...</h1>

PHP

<? php

require "Db.php";

$db = new Db;

$ipp = 10;

$pagina = (isset($_GET['pagina'])) ? (int) $_GET['pagina'] : 0;

$itens = $pagina * $ipp;

$ret = $db - > query(sprintf("SELECT codigo, titulo, texto, imagem FROM post LIMIT %d OFFSET %d", $ipp, $itens));

if ($ret - > num_rows > 0) {
  // retorna os dados para a tela no formato json

  $retorno = array();

  while ($post = $ret - > fetch_assoc()) {
    $retorno[] = $post;
  }

  response(array("erro" => false, "inicio" => $itens + 1, "fim" => $itens + $ret - > num_rows, "itensporpagina" => $ipp, "posts" => $retorno));

} else {
  // retorna erro = true no formato json para a tela
  response(array("erro" => true));
}

// retorna dados no formato json para a tela do sistema
function response($response) {
  header("Content-Type: application/json");
  echo json_encode($response);
}

jquery

var pagina = 0;

function loadPosts() {
  $("#carregando").show();

  $.ajax({
    url: "dados.php?pagina=" + pagina,
    dataType: "json"
  }).done(function(data) {
    $("#carregando").hide();

    if (data.erro) return;

    var divposts = $("#posts");

    $.each(data.posts, function(key, val) {
      divposts.append("<div style='display:table; width:100%'><img src='" + val.imagem + "' align='left' style='margin-right:10px; margin-bottom:10px;' /><h2>" + val.titulo + " / " + val.codigo + "</h2><p>" + val.texto + "</p></div>");
    });

    pagina++;

  });

}

$(function() {
  $("#carregando").hide();

  loadPosts();

  $(window).scroll(function() {
    if ($(window).scrollTop() == $(document).height() - $(window).height()) {
      // carrega os posts   
      loadPosts();
    }
  });

});
    
asked by anonymous 03.07.2018 / 20:40

2 answers

2

Remove the second $("#carregando").hide(); (within $(function() { ) you do not need.

The $("#carregando").show(); you change to $("#carregando").stop().show(); . .stop() prevents crashes in the method.

And after $.each put $("#carregando").delay(1000).hide(0); . This will give a small delay of 1 second for carregando... to disappear (you can decrease or increase the time if you want).

The script to remove the elements that leave the screen:

$(function(){

   loadPosts();

   $(window).scroll(function() {
      if ($(window).scrollTop() == $(document).height() - $(window).height()) {
        loadPosts();
      }

     $.each($("#posts div"), function(){
       var dist = $(this).offset().top-$(window).scrollTop(); // verifica a distância do elemento ao topo
       // remove todos os elementos fora da tela
       if(dist > $(window).height()) $(this).remove();
    });

   });
});

Illustrative example without Ajax:

function loadPosts(){
   $("#carregando").stop().show();
   $("#posts").append('<div>div 2</div>');
   $("#carregando").delay(1000).hide(0);

}

$(function(){
   
   loadPosts();

   $(window).scroll(function() {
      if ($(window).scrollTop() == $(document).height() - $(window).height()) {
        loadPosts();
      }
    
     $.each($("#posts div"), function(){
       var dist = $(this).offset().top-$(window).scrollTop();
       if(dist > $(window).height()) $(this).remove();
    });
   
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="carregando" style="position: fixed; right: 0; background: red; display: none;">carregango..</div>
<div id="posts">
   <div>div 0</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
   <div>div 1</div>
</div>
    
04.07.2018 / 00:23
2

Within your loadPosts function, check for more than '0' data in the response:

function loadPosts() {
  $("#carregando").show();

  $.ajax({
    url: "dados.php?pagina=" + pagina,
    dataType: "json"
  }).done(function(data) {
    $("#carregando").hide();

    if (data.erro) return;

    var divposts = $("#posts");
    if(data.posts.length > 0){
          $.each(data.posts, function(key, val) {
          divposts.append("<div style='display:table; width:100%'><img src='" + val.imagem + "' align='left' style='margin-right:10px; margin-bottom:10px;' /><h2>" + val.titulo + " / " + val.codigo + "</h2><p>" + val.texto + "</p></div>");
        });

        pagina++;
    }else{
        $("#carregando").hide();
    }

  });

}
    
04.07.2018 / 00:13