I have a page that returns 16 records from my table.
As the user scrolls to the bottom, I then pull another 12 records from my table and append them to my previous results, my problem is that my results are being duplicated, and not in the correct order.
JS
// Ajax Getentries.php
var url = location.pathname;
if(url.indexOf('missing-people.php') > -1) {
didScroll = false;
$(window).scroll(function () {
didScroll = true;
});
setInterval(function () {
if(didScroll) {
didScroll = false;
if(($(document).height() - $(window).height()) - $(window).scrollTop() < 100) {
var number = $(".directory").children().length;
$.ajax({
type: "POST",
url: "getentries.php",
data: "count=" + number,
success: function (results) {
$('.directory').append(results).fadein();
}
});
}
}
}, 250);
}
PHP
$result = mysql_query("SELECT * FROM directory LIMIT {$_POST['count']},12");
$c = 1;
while($row = mysql_fetch_array($result))
{
echo '<div class="entry';
if (($c % 4) == 1) echo ' alpha ';
echo ' span3"><span class="name">' . $row['First_Name'] . ' ' . $row['Surname'] . "</span>";
echo '<a href="/missing-people/' . strtolower($row["Location_County_Last_Seen"]) . '/' . strtolower($row["First_Name"]) . '-' . strtolower($row["Surname"]) . '/' . $row["ID"] . '"><img src="/access/upload/' . $row["picture_1"] . '" alt="' . $row['First_Name'] . ' ' . $row['Surname'] . ', missing since ' . $row['Date_Last_Seen'] . ' " /></a>';
echo '<span class="missing-from">Last seen in ' . ucwords($row["Location_County_Last_Seen"]) . '</span><a href="/missing-people/' . strtolower($row["Location_County_Last_Seen"]) . '/' . strtolower($row["First_Name"]) . '-' . strtolower($row["Surname"]) . '/' . $row["ID"] . '">View Profile</a></div>';
$c++;
}
mysql_close($con);
it seems like it's a race condition. Indeed, if you quickly scroll the page this is what happens:
var number = $(".directory").children().length
is 12.Now, if I'm still at the bottom of the page and the ajax calls hasn't completed yet, the setInterval is going to be triggered again, number
still resolve to 12 and I'm going to do the same ajax request. Hence duplication.
Solving the issue could be as simple as setting number
at the beginning of the script and incrementing it every time you make an ajax call.
// Ajax Getentries.php
var url = location.pathname;
var number = $(".directory").children().length;
if(url.indexOf('missing-people.php') > -1) {
didScroll = false;
$(window).scroll(function () {
didScroll = true;
});
setInterval(function () {
if(didScroll) {
didScroll = false;
if(($(document).height() - $(window).height()) - $(window).scrollTop() < 100) {
number += 12;
$.ajax({
type: "POST",
url: "getentries.php",
data: "count=" + number,
success: function (results) {
$('.directory').append(results).fadein();
}
});
}
}
}, 250);
}