Length of jQuery does not update with the append, how to resolve?

Asked

Viewed 269 times

3

I am working on a script that makes it load more records from the database when the user arrives at the end of the page scrolling.

PHP/SQL is right, the problem is that jQuery does not correctly report the number of completed occurrences class onscreen.

I imagine the solution is to implement the .on somehow, but I don’t know much about jQuery and I’m hitting myself with it.

I explain my code below:

$(document).ready(function() {
  var posicaoAtual = $(window).scrollTop();
  var documentSize = $(document).height();
  var sizeWindow = $(window).height();

  $(window).scroll(function() {
    posicaoAtual = $(window).scrollTop();
    //Até aqui, apenas verifico se o usuário chegou ao final da página. 

    if (posicaoAtual >= (documentSize - sizeWindow)) {
      //Agora que começa o sofrimento

      // Conta a quantidade de vezes que a section.empresa aparece na tela
      var qtdRegistros = $("#empresas section.empresa").length;

      //Variável que utilizo no meu PHP
      var idClientes = $("#idClientes").val();

      // Faz requisição ajax
      $.post("carrega-registros.php", {
        qtdRegistros: qtdRegistros,
        idClientes: idClientes
      }, function(resposta) {
        // Coloca o conteudo na DIV
        $("#empresas").append(resposta);
      });
    }
  });

  $(window).resize(function() {
    posicaoAtual = $(window).scrollTop();
    documentSize = $(document).height();
    sizeWindow = $(window).height();
  });
});

[EDIT 1]

The whole code works right. My return are new section class='empresa' within the div id="empresas".

BUT BY var qtdRegistros = $("#empresas section.empresa").length;, the variable qtdRegistros only identifies the number of times the class empresa in the original HTML. Disregarding what comes from append. This makes my PHP bring duplicate results, since the qtdRegistros is always the same.

I need to update the length according to the new class who comes in the append. But that doesn’t happen.

Researching a lot I found something similar implementing the on, but I just couldn’t use it. Someone can show me a way?

  • You can ask the question the content of resposta?

  • Hi Sergio! The script has no errors. What happens is that the same PHP pro value of the qtdRegistros variable always goes. So instead of me bringing in new records in the append, they always come back the same.

  • @Aryanavalcanaia the return of the post is a html?

  • That’s right :) The return is an append of a snippet like this "<Section class="company" id="11216"> (...) </Section>" in div #companies.

  • What seems to happen is that you are taking the same element and the append does not update the set of elements within it, but ensemble of his children. Try $("#empresas").children().length and see if it solves your problem...

  • I found a solution but for the version 1.10 jquery, what version Voce uses?

  • @Rafaelacioly v2.1.1. But I believe I have solved with Felipe’s solution :) soon return here. Thank you very much!

  • 1

    @Felipeavelar I believe it worked! It seems that my function to check if the user has reached the end of the page is that it is a bit buggy now :( I will do some tests and confirm if it is the solution! Thank you.

  • Hi Aryana. From what I understand you want the exact amount of elements before doing Ajax, that’s it?

Show 4 more comments

2 answers

1

When to insert a new elemento HTML with the append insert passing it as an object jquery, see:

$( document.body )
  .click(function() {
    $( this ).append( $( "<div class='mydiv'>" ) );
    var n = $( "div.mydiv" ).length;
    $( "span" ).text( "There are " + n + " divs. Click to add more." );
  })
 
  // Trigger the click to start
  .click();
  body {
    cursor: pointer;
    min-height: 100px;
  }
  div {
    width: 50px;
    height: 30px;
    margin: 5px;
    float: left;
    background: blue;
  }
  span {
    color: red;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>
<div class="mydiv"></div>

This example was found in documentation impaired function size()

In your case it would be something like:

...
var qtdRegistros = $("#empresas section.empresa").length;
...
$("#empresas").append($('resposta'));

Try to change also the order of the lines, first insert with append and then the count.

1


What happens is that the append does not update the amount of elements within the set of the element you are accessing, but rather the number of children of that element.

To solve this problem, change the line:

var qtdRegistros = $("#empresas section.empresa").length;

To the next:

var qtdRegistros = $("#empresas").children().length;
  • My code compiles "right". I believe there is another problem in it (https://answall.com/questions/257693/voltar-a-executar-o-jquery-apenas-depois-de-um-tempo) :/ but you have helped a lot, thank you!

  • I will justify my downvote: this suggestion does not change the code, only changes 6 by half dozen.

Browser other questions tagged

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