Reputation: 351
Recently i developed a load more functionality using php and jquery . Please see my code
Html
<div class="container clearfix product-output">
</div>
jQuery
$.ajax({
method: "POST",
url: "result.php",
data: { keyword:"all"}
}).done(function( msg ) {
$( ".product-output" ).html(msg);
$(".load-more").on("click",function(){
var load_num= $('.load-more').length;
var appear=[];
$(".im-product-block").each(function(){
appear.push($(this).attr('id'));
});
$.ajax({
method: "POST",
url: "result.php",
data: { keyword: "all", y_id: appear, load_num: load_num }
}).done(function(msg1){
$('.load-more-div').before(msg1);
if($(".hide-load").val()==1){
$(".load-more").hide();
}
});
});
});
In result .php
i write the db connection code and following query .
$query = 'SELECT * FROM `product` ORDER BY id DESC LIMIT 15';
$query_1 = 'SELECT * FROM `product` ORDER BY id DESC';
if (ISSET($_POST['y_id'])) {
$appear = implode("', '", $_POST['y_id']);
$query = "SELECT * FROM `product` WHERE id NOT IN('{$appear}') ORDER BY id DESC LIMIT 15";
$query_1 = "SELECT * FROM `product` WHERE id NOT IN('{$appear}') ORDER BY id DESC";
}
$result = $conn->query($query);
$result_1 = $conn->query($query_1);
$total_num = $result_1->num_rows;
echo '<div class="container clearfix product-output">';
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) { ?>
<div class="col-sm-2 im-product-block" id="<?php echo $row["id"]; ?>">
<p class="product-name"> <?php echo $row["name"]; ?></p></div>
<?php }
echo '</div>';
if ($total_num > 15 && $_POST[load_num] == 0) {
echo '<div class="load-more-div"><p class="load-more"> Load More</p></div>';
}
if ($total_num < 15) {
echo '<input type="hidden" name="hide-load" class="hide-load" value="1">
<div class="load-finished"><p class="load-f"> All Products Loaded Successfully</p></div>';
}
}
Here all this functionality is working fine . But instead of clicking load more button , when user scroll down to load-more it need to fetch the products automatically without clicking .
for that i using the following code
$(window).scroll(function() {
var hT = $(".load-more").offset().top,
hH = $(".load-more").outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
$(".load-more").trigger("click");
}
});
But here the execution is contunied to infinity .It is not stopping . Please check this code and suggest a good method
Upvotes: 2
Views: 1340
Reputation: 7900
I think you need to stop your load executing while your ajax call is made and written to the page. Perhaps set a boolean variable to decide if you need to load more.
e.g.
var canLoad = true;
$(window).scroll(function() {
var hT = $(".load-more").offset().top,
hH = $(".load-more").outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH) && canLoad){
canLoad = false;
$(".load-more").trigger("click");
}
});
Set canLoad
back to true once your ajax function has finished and you have loaded the data.
Upvotes: 1