0

I intend to load more items from database using Ajax infinite scroll. When I scroll to the bottom of div with id=results, the ajax works fine the first time and appends rows 21-31 from database. Note: offset = 20 and limit = 10. Offset is set to change to 30 (ie. offset +=10) after callback. However, on further scroll, offset value did not change. same rows 21-31 was repeatedly returned again and again severally. Please how do I resolve this?

index.php

<div class="row" id="result">
<?php 

$offset=0;
$limit = 20;

$query =$con->prepare("SELECT xxx FROM yyy LIMIT ? OFFSET ?");
$query->bind_param('ii', $limit, $offset);
$query->execute();
$result = $query->get_result();

while($row=$result->fetch_assoc()){
?>

    <div class="col-md-3 mb-4">  
        <div class="card-deck h-100">      
            <div class="card border-secondary">
                <img src="<?php echo $row['ppp']; ?>" class="card-img-top img-fluid">
                <div class="card-body">
                    <h6 class="font-weight-bold text-secondary text-center mt-1"><?= $row['mmm']; ?></h6>
                    <hr class="mt-1 mb-1">
                    <h6 class="card-title text-danger">NGN<?= number_format($row['nnn']); ?> /-
                    </h6>
                    <hr class="mt-1 mb-1">
                    <small class="text-secondary">Fabric Used: <?php echo $row['fff'];?>
                        <br>                                                
                    </small>
                            
                    <a href="product-details.php?ProductId=<?= $row['iii'] ?>" class="btn btn-info btn-block addItemBtn"><i class="fas fa-cart-plus"></i> Order Now</a>
                </div>
            </div>
        </div>
    </div>
<?php   
} // endwhile
?>
</div>

<div class="p-3 text-center" style="display: block" >
    <button class="btn btn-danger" type="button" disabled>
        <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span>
          Loading more items...
    </button>
</div>

<script type="text/javascript">
var flag = 20; //offset initial value 
$(window).scroll(function (){ //scroll function
    if($(window).scrollTop() >= $('#result').height() - $(window).height()){
         
        $.ajax({
              type: 'POST',
              url: 'results.php', //get result page
              data: {'offset': flag,'limit': 10},
              success: function(data){
                    $('#result').append(data);
                    flag +=10; //add 10 to last offset value after callback
           }
        }); //close ajax
    }
});
</script>

results.php

<?php 

if(isset($_POST['offset']) && isset($_POST['limit'])){
    $offset = $_POST['offset'];
    $limit = $_POST['limit'];

    if($sql = "SELECT xxx FROM yyy LIMIT ? OFFSET ?"){
        $query = $con->prepare($sql);
        $query->bind_param('ii', $limit, $offset);
        $query->execute();
        $result = $query->get_result();
        while($row=$result->fetch_assoc()){
?>
            <div class="col-md-3 mb-4">         
                <div class="card-deck h-100">      
                    <div class="card border-secondary">
                       <img src="<?= $row["ppp"] ?>" class="card-img-top img-fluid">
                        <div class="card-body">
                            <h6 class="font-weight-bold text-secondary text-center mt-1"><?= $row["mmm"] ?></h6>
                            <hr class="mt-1 mb-1">
                            <h6 class="card-title text-danger">NGN <?= number_format($row["nnn"]) ?>
                            </h6>
                            <hr class="mt-1 mb-1">
                            <small class="text-secondary">Fabric Used: <?= $row["fff"] ?></small>
                            <br>
                            <a href="product-details.php?ProductId=<?= $row['iii'] ?>" class="btn btn-info btn-block addItemBtn"><i class="fas fa-cart-plus"></i> Order Now</a>
                        </div>
                    </div>
                </div>
            </div>
<?php
        } // endwhile
    }//end if query successfull
    else{
        echo "Query Failed";
    }
}//end isset 
?>
Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

0

Use a variable to detect if you're in the middle of an AJAX request, so you don't send a duplicate.

let in_ajax = false;

$(window).scroll(function() { //scroll function
  if (!in_ajax) {
    if ($(window).scrollTop() >= $('#result').height() - $(window).height()) {
      in_ajax = true;
      $.ajax({
        type: 'POST',
        url: 'results.php', //get result page
        data: {
          'offset': flag,
          'limit': 10
        },
        success: function(data) {
          $('#result').append(data);
          flag += 10; //add 10 to last offset value after callback
          in_ajax = false;
        }
      }); //close ajax
    }
  }
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • thanks @barmar. Worked. Now I want to add bootstrap spinner the spinner but not working. Can you help pls? See what i did in the edited code. – codes4life Jan 05 '21 at 10:22
  • Please don't change the question to match the answer. My answer makes no sense if people can't see your original code. – Barmar Jan 05 '21 at 15:02
  • If you have a new problem, post another question. – Barmar Jan 05 '21 at 15:03
  • I have asked the new question here. Pls help. Thanks https://stackoverflow.com/questions/65582759/bootstrap-spinner-not-working-before-and-after-ajax-call – codes4life Jan 05 '21 at 16:28