Sankalp
Sankalp

Reputation: 1128

jscroll load data when at the end

I have some UI element that needs infinite scrolling. So I am using jscroll. I want to fetch new data when the div is at the end.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script src=js/jquery.jscroll.js></script>
<script>

$('.scrollt').jscroll(function(){
    $(".scrollt").load("/handle.php?lastdis=90");});

</script>
</head>
<body>


<?php
include_once('conn.php');

$start=0;
$query="Select * from data where id > ". $start ." Limit 90;";
$res=mysqli_query($con,$query);

echo '<div class="scrollt">';
while ($row = mysqli_fetch_array($res, MYSQL_NUM)) {
    echo "<p> ".$row[0]." &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;". $row[1]."<p><p><p>";
}

echo "</div>"

?>

</body>
</html>

So basically I display a page with 90 records and want to fetch records above 91 in load() function.But this doesn't work.

handle.php code

<?php
include_once('conn.php');
$goahead=$_GET['lastdis'];

$query="Select * from data where id > ". $goahead ." Limit 20;";
$res=mysqli_query($con,$query);
while ($row = mysqli_fetch_array($res, MYSQL_NUM)) {
    echo "<p> ".$row[0]." &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;". $row[1]."<p><p><p>";
}

Just two hours of jquery experience.Please bear with me.

Upvotes: 1

Views: 3117

Answers (1)

Optimus Prime
Optimus Prime

Reputation: 6907

Use the .scroll() event on window, like this:

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
       alert("bottom!");
   }
});

You can test it here, this takes the top scroll of the window, so how much it's scrolled down, adds the height of the visible window and checks if that equals the height of the overall content (document). If you wanted to instead check if the user is near the bottom, it'd look something like this:

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
       alert("near bottom!");
   }
});

You can test that version here, just adjust that 100 to whatever pixel from the bottom you want to trigger on.

Now, just instead of alerting the user at bottom use ajax to get the data you want to append at bottom.

  $.ajax({
      url: "handle.php",
      type: "post",
      data: values,
      success: function(data){
           $("#result").append(data);
      },
      error:function(){
          alert("failure");
          $("#result").append('Error Occurred while fetching data.');
      }   
    }); 

Upvotes: 5

Related Questions