Php Geek
Php Geek

Reputation: 1107

Passing dynamic values through ajax

I hav this code in jquery which is written in such a way that when i scroll down my mouse next set of records are fetched from db and displayed. Initially my page shows 25 records, and when i scroll down next 15 records r fetched from db. My problem is that i am not able set a counter and increment the counter whenever scroll function is called. And also when ever i scroll down same 15 records r displayed. This is my code...

$(window).on('scroll',function(){
  if($(window).scrollTop()==($(document).height()-$(window).height())){

    $.ajax({
        type: 'POST',
        url: 'getdata.php',
        success: function(nxt_data){
           $('#data').append(nxt_data);
        }
    });
  } 
}); 

Upvotes: 0

Views: 533

Answers (2)

PassKit
PassKit

Reputation: 12581

Your issue appears to be because getdata.php has no way of knowing what records to return, so it is just returning the same 15 rows.

var counter=25;

$(window).on('scroll',function(){
  if($(window).scrollTop()==($(document).height()-$(window).height())){

    $.ajax({
        type: 'GET',
        url: 'getdata.php?start_row=' + counter,
        success: function(nxt_data){
           $('#data').append(nxt_data);
           counter += 15;
        }
    });
  } 
}); 

In your PHP file you can access the counter variable using $_GET['start_row'];

Upvotes: 1

Adam Merrifield
Adam Merrifield

Reputation: 10407

Create a page variable and then add to it everytime the ajax is called.

var page = 1;
$(window).on('scroll', function () {
  if ($(window).scrollTop() == ($(document).height() - $(window).height())) {
    page++;

    $.ajax({
      type: 'POST',
      data: 'page=' + page,
      url: 'getdata.php',
      success: function (nxt_data) {
        $('#data').append(nxt_data);
      }
    });
  }
});

Upvotes: 2

Related Questions