EnexoOnoma
EnexoOnoma

Reputation: 8836

How to load more on PHP array?

I use jQuery (I found this code in an answer, tested and working) to show people.php and reload it every 100 seconds. People.php has an array peoples where there are saved name, job, birthday.

As you can see, the output stops at 30 names. How can I have a twitter like button "load more" and show 10 more at a time? Additionally, when there are e.g. 50 more people's name (assuming that the user clicked "load more" twice, will the jQuery timeout reload, returned them at 30 as the beginning ?

<script>
var timerID;

$(function () {
    function loadfeed() {
        $('#feed')
            .addClass('loading')
            .load('people.php', function () {
                $(this).removeClass('loading');
                timerID = setTimeout(loadfeed, 100000);
        });
    }

    loadfeed();
});
</script>

Upvotes: 0

Views: 1338

Answers (2)

Rusty Fausak
Rusty Fausak

Reputation: 7525

How about passing a parameter to the URL in your load(..) call?

$(function () {
    var startAt = 0;
    function loadfeed() {
        $('#feed')
            .addClass('loading')
            .load('people.php?start_at=' + startAt, function () {
                $(this).removeClass('loading');
                timerID = setTimeout(loadfeed, 100000);
                startAt += 30;
            });
    }
});

Then in people.php you could get the passed parameter using $_GET:

$start_at = 0;
if (isset($_GET['start_at']) && is_numeric($_GET['start_at'])) {
    $start_at = (int) $_GET['start_at'];
}
for ($i = $start_at; $i < min($start_at + 30, sizeof($peoples)); $i++) {
    echo $peoples[$i]->name;
}

Upvotes: 1

Wesley
Wesley

Reputation: 2200

Well what you could do is save a variable that contains the number of people, this example should give you a good view of what i mean.

<script>
var timerID;
var cap;

$(function () {
    function loadfeed() {
        $('#feed')
            .addClass('loading')
            .load('people.php?cap='+cap, function () {
                $(this).removeClass('loading');
                timerID = setTimeout(loadfeed, 100000);
        });
    }

    loadfeed();
});
</script>

<?php
    foreach ($peoples as $people) {
    if(++$i > $_GET['cap']) break;

    echo $people->name;

    }
?>

So all you have to do, is change the cap variable, you could do this easily making a javascript function and call this via a onClick event.

Upvotes: 0

Related Questions