user3475724
user3475724

Reputation:

AJAX function is not working by scroll

Using AJAX for endless scroll. Content loads only first time, but does't load by scroll.

What is wrong?

jQuery:

function loadFeed() {
    $.ajax({
        url: 'loadmore.php',
        dataType: 'html',
        success: function (data) {
            $("#posts").append('<div class="havanagila"></div>');
            $('#posts').html(data);
        }
    });
}

loadFeed();
$(window).scroll(function () {
    var windowScroll = $(window).scrollTop();
    var windowHeight = $(window).height();
    var documentHeight = $(document).height();

    if ((windowScroll + windowHeight) == documentHeight) {
        loadFeed();
    }
});

loadmore.php:

<?php 
session_start();

if ( isset( $_SESSION['login'] ) ) {

    $login    = $_SESSION['login'];
    $id=$_SESSION['id'];

    $username="root";
    $password="root";
    $hostname = "localhost";
    $dbname= "kotik";


    function testdb_connect ($hostname, $username, $password){
        $dbh = new PDO("mysql:host=$hostname;dbname=kotik", $username, $password);
        return $dbh;
    }


    try {
        $dbh = testdb_connect ($hostname, $username, $password);

    } catch(PDOException $e) {
        echo $e->getMessage();
    }

}

?>

<?php                                                              

$title_select_query= $dbh -> prepare("SELECT title FROM books WHERE id = :id ORDER BY date DESC");
$title_select_query ->execute(array(':id' => $id));
$title_select_query_result = $title_select_query->fetchColumn(); 
echo($title_select_query_result);

$title_select_query_result = $title_select_query->fetchColumn(); 
echo($title_select_query_result);

$title_select_query_result = $title_select_query->fetchColumn(); 
echo($title_select_query_result);

$title_select_query_result = $title_select_query->fetchColumn(); 
echo($title_select_query_result);

$title_select_query_result = $title_select_query->fetchColumn(); 
echo($title_select_query_result);

?>

Upvotes: 25

Views: 3542

Answers (8)

Abdul Manan
Abdul Manan

Reputation: 2375

Everything look fine to me,

Just Change $(window).scroll(function () {...... to

$(document).on( 'scroll','window', function(){
              //or $(document).on( 'scroll','id of div containing scroll',
   var windowScroll = $(window).scrollTop();
   var windowHeight = $(window).height();
   var documentHeight = $(document).height();

    if ((windowScroll + windowHeight) == documentHeight) {
         loadFeed();
       }
});

Upvotes: 0

JESTIN6699
JESTIN6699

Reputation: 49

The following javascript code is used to load 4 records when the scroll bar hit at the bottom of screen. That means when first time 4 records will fetched, second time next 4 records fetched and these all records will displayed on the screen. This code help us to decrease the load lag at page load time.

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
       //alert("bottom!");
       loadNext();
   }
});
var n1=0;
var n2=4;

function loadFirst()
{
    var n1=0;
    var n2=4;   
}
function loadNext()
{
    n1=n1+4;
    n2=n2+4;
    //alert(n1);    
    //alert(n2);
    if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("testidiv").innerHTML=document.getElementById("testidiv").innerHTML+xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","next_testimonial_action.php?a=" + n1 + "&b=" + n2,true);
xmlhttp.send();

}


</script>

"next_testimonial_action.php?a=" + n1 + "&b=" + n2" is the php page that contains logic for fetching data from db, and n1,n2 are the limit of the records to be fetched. If you need the php file you can request as a comment. Thank you

---- Important---- "You must call loadFirst() function at bodyOnload or document.ready() jquery"

Upvotes: 2

Han
Han

Reputation: 3324

It looks that you overwrote the inner content of element #posts by html() function. $("#posts").append('<div class="havanagila"></div>'); $('#posts').html(data);

I think you want $("#posts").append($('<div class="havanagila"></div>').html(data));

And about your IF statement if ((windowScroll + windowHeight) == documentHeight), your ajax function is called only if you scroll from the top to the bottom of the page (on Chrome).

Upvotes: 2

vasilenicusor
vasilenicusor

Reputation: 2073

Because you replace the content of $('#posts'), the height of document does not change after first ajax request on scroll => so you need to scroll up , and then scroll down again to trigger another ajax request. Because i don't know the expected page layout, i will give a simple basic demo HTML JSFiddle demo

<div id="main" style="height:200px; overflow-y : auto;">
    <div id="posts">
    </div>
</div>

javascript

var loadmoore = true,
    loaded_posts =0 ;
function gent_sample_data(num_posts){
    var i,
        sample_data = '';
    for(i=0;i<num_posts;i++) {
        sample_data += "<p class'post'>title_select_query_result " + (loaded_posts + i) + "</p>"; 
    }
    return sample_data;
}

function loadFeed(){
     // generate sample data
    var sample_data = gent_sample_data(15);
    loaded_posts = loaded_posts + 15;
    $.ajax({
        url : '/echo/html/',
        dataType: 'html',
        type: 'post',
        data: {'html':sample_data},
        success: function(returnhtml){
            console.log(returnhtml);
             // option 1 - add result into "havanaglia" div
            // var $post = $('<div class="havanagila"></div>');
            // $post.html(returnhtml);
            // $("#posts").append($post);

            // option 2 - ad result after "havanaglia" div
            $("#posts").append('<div class="havanagila"></div>');
            $("#posts").append(returnhtml); 
            loadmoore = true;
        }    
    });
}
loadFeed();

$("#main").scroll(function () { 
    if (loadmoore && $("main").scrollTop() >= ($("main").height()-100) ) {
       loadmoore = false;
       loadFeed();
    }
});

For your case I suggest to use something like this:

var loadmoore= true;
function loadFeed() {
    $.ajax({
        url: 'loadmore.php',
        dataType: 'html',
        success: function (data) {
            var $havanaglia = $('<div class="havanagila"></div>');
            $havanaglia.html(data);
            $("#posts").append($havanaglia);
            loadmoore = true;
        }
    });
}

loadFeed();

$(window).scroll(function () { 
    if (loadmoore && $(window).scrollTop() >= $(document).height() - $(window).height()-100) {
        loadmoore= false;
       loadFeed();
    }
});

To prevent to get the same posts from database i recommend to send to php the id/number of last loaded post to get posts with id/number > last loaded post

Upvotes: 13

Varun Naharia
Varun Naharia

Reputation: 5420

change you loadFeed() funtion to this

function loadFeed() {
    $.ajax({
        url: 'loadmore.php',
        dataType: 'html',
        success: function (data) {
            $("#posts").append('<div class="havanagila"></div>');
            $('#posts').html($('#posts').html()+data);
        }
    });
}

this is the change you have to do $('#posts').html($('#posts').html()+data);

Upvotes: 6

Karthikeyan S
Karthikeyan S

Reputation: 1

function loadFeed() {
    $.ajax({
        url: 'loadmore.php',
        dataType: 'html',
        success: function (data) {
            $("#posts").append('<div class="havanagila"></div>');
            $('#posts').html(data);
            $(window).on('scroll', function() {checkScroll()}); // Run the function again upon success
        }
    });
}

var checkScroll = function() {
  if ($('#SomeElementAlwaysAtTheBottomOfThePage')[0]) {
    var el = $('#SomeElementAlwaysAtTheBottomOfThePage');
    var bottom_of_object = el.offset().top + el.outerHeight();
    var bottom_of_window = $(window).scrollTop() + $(window).height();

    if (bottom_of_window >= bottom_of_object) { // If we're at the bottom...
      $(window).unbind('scroll'); // Stop the scroll function
      loadFeed(); // Load the AJAX
    }
  }
}

$(window).on('scroll', function() {checkScroll()}); // Start the function off
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="posts"></div>
<div id="SomeElementAlwaysAtTheBottomOfThePage"></div>

Upvotes: -2

Jamie Barker
Jamie Barker

Reputation: 8246

If I remember correctly I was suffering the same problem for something similar. What I did was to stop the scroll listener and restart it upon AJAX success.

Here's the code that could help you:

function loadFeed() {
    $.ajax({
        url: 'loadmore.php',
        dataType: 'html',
        success: function (data) {
            $("#posts").append('<div class="havanagila"></div>');
            $('#posts').html(data);
            $(window).on('scroll', function() {checkScroll()}); // Run the function again upon success
        }
    });
}

var checkScroll = function() {
  if ($('#SomeElementAlwaysAtTheBottomOfThePage')[0]) {
    var el = $('#SomeElementAlwaysAtTheBottomOfThePage');
    var bottom_of_object = el.offset().top + el.outerHeight();
    var bottom_of_window = $(window).scrollTop() + $(window).height();

    if (bottom_of_window >= bottom_of_object) { // If we're at the bottom...
      $(window).unbind('scroll'); // Stop the scroll function
      loadFeed(); // Load the AJAX
    }
  }
}

$(window).on('scroll', function() {checkScroll()}); // Start the function off
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="posts"></div>
<div id="SomeElementAlwaysAtTheBottomOfThePage"></div>

Upvotes: 5

Jayson
Jayson

Reputation: 1109

If you want to load AJAX function for each scroll event there is no need to check if condition. simply write..

$(window).scroll(function(){
        loadFeed();
});

and if you want to call the AJAX function if the scroll has reached the bottom you have to check condition like...

$(window).scroll(function(){
    if ($(window).scrollTop() == $(document).height() - $(window).height()){
        loadFeed();
    }
});

Upvotes: 6

Related Questions