Infinit Scroll - does not bring all BD data

Asked

Viewed 294 times

0

I am trying to implement an Infinit scroll in my project, but I am having difficulty solving this problem

the connection is perfect and I’m receiving the information from BD, but the code only shows one entry, what I must change to solve this?

Code index.php

<!DOCTYPE html>
<html>
    <head>
            <meta charset="utf-8">
            <title>jQuery Infinite Scroll</title>
    </head>
    <body>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
            <script type="text/javascript">
            var start = 0;
            var working = false;
            $(document).ready(function() {
                    $.ajax({
                            type: "GET",
                            url: "data.php?start="+start,
                            processData: false,
                            contentType: "application/json",
                            data: '',
                            success: function(r) {
                                    r = JSON.parse(r)
                                    for (var i = 0; i < r.length; i++) {
                                            $('body').append("<div><h1>"+r[i].videoName+"</h1><h2>Video View: "+r[i].videoViews+"</h2></div>")
                                    }
                                    start += 6;
                            },
                            error: function(r) {
                                    console.log("Something went wrong!");
                            }
                    })
            })
            $(window).scroll(function() {
                    if ($(this).scrollTop() + 1 >= $('body').height() - $(window).height()) {
                            if (working == false) {
                                    working = true;
                                    $.ajax({
                                            type: "GET",
                                            url: "data.php?start="+start,
                                            processData: false,
                                            contentType: "application/json",
                                            data: '',
                                            success: function(r) {
                                                    r = JSON.parse(r)
                                                    for (var i = 0; i < r.length; i++) {
                                                            $('body').append("<div><h1>"+r[i].videoName+"</h1><h2>Video View: "+r[i].videoViews+"</h2></div>")
                                                    }
                                                    start += 6;
                                                    setTimeout(function() {
                                                            working = false;
                                                    }, 4000)
                                            },
                                            error: function(r) {
                                                    console.log("Something went wrong!");
                                            }
                                    });
                            }
                    }
            })
            </script>
    </body>
    </html>

Data code.php:

<?php

class Video {
    public $videoName = "";
    public $videoViews = "";

    public function __construct($videoName, $videoViews) {
            $this->videoName = $videoName;
            $this->videoViews = $videoViews;
    }
}
$conectar = mysqli_connect("localhost", "***", "***", "***") or die("Erro 001 - Conection lost");
if ($conectar->connect_errno) {
     echo "Falha ao conectar com o mysql: (" . $conectar->connect_errno . ") " . $conectar->connect_error;
}

$start = $_GET['start'];
$data = array();
$query = "SELECT * FROM videos ORDER BY id DESC";
$resultado = mysqli_query($conectar, $query);
while($linhas = mysqli_fetch_assoc($resultado)){


$possibleVideos = array(
     new Video($linhas['nome'],$linhas['tempo']),
    );

    }

for ($i = $start; $i < $start+6; $i++) {
    if ($i < count($possibleVideos)) {
            array_push($data, $possibleVideos[$i]);
    }
}

//echo "<pre>";
echo json_encode($data);
?>
  • 1

    Why not use OFFSET of MySQL or SELECT * FROM videos ORDER BY id DESC LIMIT $start, 5;?

  • can’t do, I was learning in a tutorial until it came to this

  • 1

    Try with the code SELECT ... that I posted and see if it solves something. With it you nay will need the for ($i = $start; $i < $start+6; $i++) ...

  • unfortunately it did not work, replacing SELECT... and removing the for ($i... the page is blank, does not carry any record

  • 1

    Is you are not assigning the values in the variable $date. Complete example: https://pastebin.com/HJ37Rram

  • he is bringing the amount of entries but does not bring the information, all records are listed as Undefined

  • 1

    Add console.log(r); before r = JSON.parse(r) and check on the tab Console (F12) what the result is. I changed my code in the link above.

  • Sensational friend, works perfectly, thank you very much!

  • I came across a problem when I tried to implement the code to the project, the problem is that the entries load at the bottom of the page and not within the <div class="Row"> that the scrypt is found... any idea that can help me? @Valdeirpsr

  • @For this, just create the div where you want to put the element,assign an id to it and then do the following: $('#your-div'). append(result)

Show 5 more comments

1 answer

1

Use the OFFSET or the LIMIT to capture from a given record. Ex:

/* Dessa forma você irá capturar os 5 primeiros registros */
SELECT * FROM `users` LIMIT 5;

/* Dessa forma você irá capturar os 5 primeiros registros após o décimo registro */
SELECT * FROM `users` LIMIT 5 OFFSET 10;

/* Mesma coisa que o item acima */
SELECT * FROM `users` LIMIT 10, 5;

As your variable $start will always receive a offset, then just use this mode. This will save server resources.

Imagine if you had more 10,000 posts. Having to return 10,000 several times and then catch only the last ones. Now imagine 1,000 people accessing your site at the same time...

Complete and refactored code:

<?php

$conectar = mysqli_connect("localhost", "***", "***", "***") or die("Falha ao conectar com o mysql: (" . $conectar->connect_errno . ") " . $conectar->connect_error);

/* Verifica se o parâmetro `start` existe, caso não exista adiciona 0 à variável */
$start = isset($_GET['start']) ? $_GET['start'] : 0;

$data = array();

$query = "SELECT * FROM videos ORDER BY id DESC LIMIT {$start}, 5";

$resultado = mysqli_query($conectar, $query);

if ( $error = mysqli_error($conectar) ) {
    die( $error );
}

while($linhas = mysqli_fetch_assoc($resultado)){
    $data[] = array(
        "videoName" => $linhas['nome'],
        "videoViews" => $linhas['tempo']
    );
}

echo json_encode($data);

To add this data within the div.row, it is necessary to replace $('body').append() for $('div.row').append().

But this is not recommended. If you have more than one div with class row, the text will be added to all of them. Ideally, always use the attribute id for that. Ex:

Html:

<div id="videos" class="row"></div>

Js:

$('#videos').append(...);

Complete and refactored example:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>jQuery Infinite Scroll</title>
    </head>

    <body>

        <div id="videos" class="row"></div>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script type="text/javascript">
            let start = 0;
            let working = false;

            $(document).ready(function() {
                loadData();
            })

            $(window).scroll(function() {
                if ($(window).scrollTop() + $(window).height() == $(document).height()) {
                    loadData();
                }
            })

            function loadData() {
                if (working == false) {                    
                    $.ajax({
                        type: "GET",
                        url: "index3.php",
                        contentType: "application/json",
                        data: {start: start},
                        beforeSend: function() {
                            working = true;
                        },
                        success: function(r) {
                            r = JSON.parse(r)

                            /* Percorre todos os valores que estão no `array` r */
                            for (data of r) {
                                $('#videos').append("<div><h1>"+data.videoName+"</h1><h2>Video View: "+data.videoViews+"</h2></div>")
                            }

                            working = false;

                            start += 6;
                        },
                        error: function(r) {
                            console.log("Something went wrong!");
                        }
                    });
                }
            }
        </script>
    </body>
</html>
  • made the changes, the data.php file is ok, but the index page, after scrolling only loads other entries once, even using Pgup and Pgdn from the keyboard.

  • @Éoronaldodll I changed the html of my reply. I removed the setTimeout and how it is checked if the user is at the bottom of the page.

Browser other questions tagged

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