javascript - PHP Infinite scroll pulling random results? -
i have page returns 16 records table.
as user scrolls bottom, pull 12 records table , append them previous results, problem results being duplicated, , not in 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 * 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 it's race condition. indeed, if scroll page happens:
- the setinterval gets triggered
- there 12 images in dom, hence
var number = $(".directory").children().length
12. - now new data fetched server ajax.
now, if i'm still @ bottom of page , ajax calls hasn't completed yet, setinterval going triggered again, number
still resolve 12 , i'm going same ajax request. hence duplication.
solving issue simple setting number
@ beginning of script , incrementing every time make 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); }
Comments
Post a Comment