Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Carlos Morales
13,880 PointsjQuery/ajax $.post request question.
I'm trying to implement infinite scroll on a site I'm building for practice and fun. I'm using jQuery and I've build a function that's triggered once the bottom of the page is hit:
$(document).ready(function(){
$(document).scroll(function(){
var load = 0; /* This is the varible I'm having trouble with. */
var scroll_top = $(this).scrollTop();
var window_height = $(window).height();
var document_height = $(document).height();
if(document_height - window_height == scroll_top){
load++;
$.post("infinite_add.php",{load:load},function(data){
$('#images').append(data);
});
}
});
});
Once triggered, this code executes:
load++;
$.post("infinite_add.php",{load:load},function(data){
$('#images').append(data);
});
The "infinite_add.php" file contains:
require_once("database.php");
$load = htmlentities(strip_tags($_POST['load'])) * 2;
$query = $db->query("SELECT * FROM a_table ORDER BY a_id DESC LIMIT ".$load.",2");
/* Then it has 'while loop' that add html with php embedded. */
Now, it works once. But after looking in the console, I noticed my load variable is not incrementing. It continues to pass back the first set of results because I cannot get it increment. Please help and thanks in advance.
2 Answers

John W
21,558 PointsLooks like every time you scroll, you are redefining load. In fact, load only exists within the scope of your scroll function, so as soon as the scroll ends, it disappears. A simple solution would be to define and initialize it outside your scroll function.

Carlos Morales
13,880 PointsJohn, Thank you for your response. The change you suggested has resolved my issue.