Infinite scrolling bug produces duplicate values and doesn't fetch all the remaining posts

i’m indulged in a project(started 5 months ago) requiring infinite scrolling pagination where i couldn’t get the javascript working because it keeps on producing duplicate posts from php script. I tried the mysql query in phpmyadmin and it didnt produce any duplicate queries and i require help in getting a seamless pagination without duplicate queries like facebook for the project to take off.

Here are the scripts that i have been working so, far.
Javascript from home page:


    var load=0;
         
         var sess_uname="<?php echo $session_uname;?>";
         var f_uname="<?php echo htmlspecialchars($_GET['u']);?>";
         var sess_count="<?php echo $total_sess_count;?>";
         var f_count="<?php echo $total_friend_count;?>";
        var funame="<?php echo $f_uname0;?>";
    $(".message").html("<div style='display: flex; justify-content: center;'><h1>Loading Posts...</h1> &nbsp;  "+spinner1+"</div>").show();
         if(sess_uname==f_uname){
             $(window).scroll(function(){
                  //alert($(window).scrollTop()); 
              // alert($(window).scrollTop()+" "+$(document).height()-$(window).height());
                 if($(window).scrollTop()==$(document).height()-$(window).height()){
                     var sub=$(document).height()-$(window).height();
          //lert(sub);
               // alert($(window).scrollTop()+"  "+sub); 
                load++;
        //  alert(load+" "+sess_count);
                 if(load * 2 > sess_count){
                     $(".message").html("<h1>no more posts to show </h1>");
                 }else{
          
                     $.post("st&com.php", {"load":load,"sess_count":sess_count},function(data){
            $(".message").html(spinner1).show();         
            $("#status_area").append(data);
                        $(".hide").hide();
            $(".message").html(spinner1).hide();            
      
        });
                 }
                 }
             });
         }else {
             $(window).scroll(function(){
               
                 if($(window).scrollTop()==$(document).height()-$(window).height()){
                 load++;
       // alert($(window).scrollTop()+"  "+$(document).height()-$(window).height());
                 if(load *2 >f_count){
                     $(".message").html("<h1>no more posts to show here</h1>");
                 }else{
                    
                     $.post("status_list.php", {funame:funame, load:load},function(data){
            $(".message").html(spinner1).show();         
            $("#status_area").append(data);
                        $(".hide").hide();
            $(".message").html(spinner1).hide();            
            
                     });
                 }
                 }
             });    
         }   
        $(document).on("click", ".close_edit",function(){
            var id=$(this).attr("type");
           $(".session_editor"+id).hide();
           $(".status_"+id).show();
           
        });

php script(it’s lengthy):


     $f = array();
      $ids=  array();
    $stmt=  $conn->prepare("select friend_one, friend_two from friends where (friend_one=:session OR friend_two=:session) and (friend_one>=:session or friend_two>=:session) and accepted='1'");
    $stmt->bindparam(":session",$_SESSION['uname']);
    $stmt->execute();
    $f=$stmt->fetchAll();
    $f_count=count($f);
    
    $ids=  ff($f, $project);
    $i=0;
   
     while($i<$f_count){    
    $id=$v;
    print_r($ids[$i]);
    //fetch username from update table in db and inject it to the feed query.
       
    
    $totalUpdates=$project->totalUpdates($ids[$i],$_SESSION['uname'] ,$load);   
      $i++;
     
        /*
    
         *we get the $sess_count and $load from javascript in home page and forward the logic if load*2 is greater than 
         * $sess_count variable if it is great then the $total_sess_count is set to 0 else it is fetched from classes.inc.php 
         *     
         */
        
        if($load*2>$sess_count){
            $total_sess_count=0;
        }
     else {
        
      $total_sess_count=$project->totalupdatescount($id);
     }
    
        
        foreach ($totalUpdates as $j=>$row1) {
       
                    $updateid=$row1['update_id'];
                    
                    $account_name=$row1['account_name'];
                    $u_id=$row1['user_id_u'];
                    $author=$row1['author'];
                    $post_date=$row1['time'];
                    $title= stripslashes($row1['title']);
                    $data= stripslashes($row1['update_body']);
                  $data1=  hashtags($data);
                  //$data1=  taggingsys($data0);
                  $pic=$project->viewByUname($author);
                  $uid=$pic['user_id'];
             $datemade = strftime("%B %d, %y", strtotime($post_date));
               $avatar=$pic['avatar'];
              if ($avatar!=""){
              $feed_pic='../user/user/'.$uid.'/'.$avatar;
          }  else {
              $feed_pic='img/avatardefault.png';
              }
              
                         $words=explode(" ", $data1);
             $count_words=count($words);
             if($count_words>180){
              $partial_data1= join(" ", array_slice($words,0,150));
              
              $more="<button class='btn btn-link more' data-id='".$updateid."'>...More</button>";
             }else{
                 $partial_data1=$data1;
                 $more="";
             }
              
              $vote_up_count=$project->voteUpdateCheck($updateid, $_SESSION['id']);
              
            if($vote_up_count[0][0]>0){
                $vote_like=TRUE;
                
            } else {
            $vote_like=FALSE;    
            }
              if($vote_up_count[0][1]>0){
                $vote_dislike=TRUE;
                
            } else {
            $vote_dislike=FALSE;    
            }
            include 'ratings/vote_count.php';
              if ( $vote_like==TRUE && $vote_dislike==FALSE) {
               
              
                 $like='<a  type="liked" class="btn btn-warning liked status_like_'.$updateid.' " attr="'.$updateid.'">Liked</a>&nbsp;<span class="label label-info">'.$num_likes[0].'</span>';
                 $unlike='<a  type="unlike" class="btn btn-danger status_unlike_'.$updateid.' " attr="'.$updateid.'">Dislike</a>&nbsp;<span class="label label-info">'.$num_unlikes[0].'</span>';   
              }
     elseif ($vote_dislike==TRUE && $vote_like==FALSE) {
                  
                 $like='<a  type="like" class="btn btn-warning status_like_'.$updateid.' like" attr="'.$updateid.'">Like</a>&nbsp;<span class="label label-info">'.$num_likes[0].'</span>';
                 $unlike='<a  type="disliked" class="btn btn-danger disliked status_unlike_'.$updateid.'" attr="'.$updateid.'">Disliked</a>&nbsp;<span class="label label-info">'.$num_unlikes[0].'</span>';
              }  else {
                 $like='<a  type="like" class="btn btn-warning status_like_'.$updateid.' like" attr="'.$updateid.'">Like</a>&nbsp;<span class="label label-info">'.$num_likes[0].'</span>';
                 $unlike='<a  type="unlike" class="btn btn-danger status_unlike_'.$updateid.' unlike" attr="'.$updateid.'">Dislike</a>&nbsp;<span class="label label-info">'.$num_unlikes[0].'</span>';
                 
              }
              $share_button="";
                     
                      $hidden_text= '<textarea class="hidden_textarea hidden_value'.$updateid.'" disabled>'.$data.'</textarea>';
                       $share_button="<a class='btn btn-primary share_btn share_".$updateid."' title='".$title."' type='share' id='".$updateid."'>Copy</a>";
                         
                 $reply_btn="";
                    if ($author==$_SESSION['uname'] || $account_name==$_SESSION['uname']) {
                    $statusdeletebutton='<li>'
                               . '<a type="'.$updateid.'" class="btn delete_4_session hidden_text_delete_'.$updateid.' glyphicon glyphicon-trash delete_status_btn" title="Delete this status and its replies">Remove</a></li>';
                    $edit_btn='<li>'
                            . '<a attr="'.$updateid.'" type="'.$updateid.'" class="btn edit_4_session hidden_text_edit glyphicon glyphicon-pencil" title="Edit this status" >Edit</a></li>';
                    $statusui_edit="<div type='".$updateid."' class='hide hidden_edit_4_session session_editor".$updateid." jumbotron'>"
                . "<a type='".$updateid."' class='btn pull-right close_edit' title='Close without editing'>Close X</a>"
                . "<input type='text' class='form-control title_s_edit title_s_".$updateid."' name='status_title' value='".html_entity_decode($title)."' placeholder='Title' >"
                . "<span>&nbsp;</span>"
                . "<textarea id='wall_edit_".$updateid."' type='".$updateid."' rows='5' cols='50'  class='session_edit text_value_".$updateid."' wrap='hard' placeholder='whats up ".$_SESSION['uname']."'>
                 ".html_entity_decode($data1)."</textarea><br>"
                . "<span class='pull-left spinner_edit".$updateid."'></span><button style='float:right;' value='".$updateid."' type='a' class='btn btn-warning btn btn-large btn-lg post-s-edit'>Update</button></div>" ;
     
                    }else{
                        $statusdeletebutton="";
                        $edit_btn="<li class='posted'>You are not the owner of this Post</li>";
                        $statusui_edit="";
                         $report_btn='<li><a href="#'.$updateid.'" attr="'.$_SESSION['id'].'" account-name="'.$author.'" type="'.$updateid.'" id="'.$f_uid.'"  class="report_offence glyphicon glyphicon-warning-sign" title="Edit this status" >Report</a></li>';
                    }
              
           echo $statusui_edit.''. $hidden_text.'<div attr="'.$updateid.'" type="'.$updateid.'" class="statusboxes border border-warning  status_'.$updateid.'  jumbotron">'
                            . '<h3 class="pull-left title">'
                            . '<div id="#'.$updateid.'" attr="'.$updateid.'" class="title_s_2copy posted" value="'.html_entity_decode($title).'">'.html_entity_decode($title).'</div></h3>'
                            . '<span class="pull-right">'
                            . '<div class="dropdown">'
                            . '<button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown"  >'
                            . '<span class="glyphicon glyphicon-edit"></span></button>'
                            . '<ul class="dropdown-menu">'
                             .$edit_btn .' '. $statusdeletebutton .''.$report_btn.'</ul></div></span><br><hr>'
                            . '<legend><span style="font-size: 13.5px;" class=" data_s_2copy" type="'.$updateid.'" >'
                            . '<div class="descrip" data-id="'.$updateid.'">'
                            . html_entity_decode($partial_data1)." <br>".$more.'</div></span></legend><b class="posted"><small>Posted by:-  <a href="home.php?u='.$author.'"><img src="'.$feed_pic.'" height="20px" width="20px"> '.$author.   '</a> on   '.$datemade.'</b>'
                            . '<br><span class="pull-left spinner_status'.$updateid.'"></span><legend>'.$like.' | '.$unlike. ' | '.$share_button.'</legend></small><span class="edit-spinner"></span>';
                           
           ?>
    <h4><a id="<?php echo $updateid;?>" class="btn btn-default collap-btn">Comments</a></h4>
        <!-- Collapsible Element HTML -->
      <div id="toggle<?php echo $updateid;?>" class="collapse scroll-comments">
         
       <?php
    // Fetch Comments of update
            $totalComments=$project->totalComments($_SESSION['uname'],$friend,$updateid);   
            foreach($totalComments as $row1){
                 $status_reply_id=$row1['comment_id'];
                    $reply_d=htmlentities($row1['comment_body']);
                    $reply_data=  stripslashes($reply_d);
                    $reply_osid=$row1['os_id'];
                    $reply_date=$row1['time_c'];
                    $reply_author=$row1['author_c'];
                    $reply_data1=  hashtags($reply_data);
                    //$reply_data1= taggingsys($reply_data0);
                    //$reply_data1=  taggingsys($reply_data0);
                    $datemade_r = strftime("%B %d, %y", strtotime($reply_date));
                      include 'ratings/vote_count4comments.php';
            
              $vote_up_count_r=$project->voteReplyCheck($_SESSION['id'], $status_reply_id);
              
            if($vote_up_count_r[0][0]>0){
                $vote_like_r=TRUE;
                
            } else {
            $vote_like_r=FALSE;    
            }
              if($vote_up_count_r[0][1]>0){
                $vote_dislike_r=TRUE;
                
            } else {
            $vote_dislike_r=FALSE;    
            }
            
            
              if ( $vote_like_r==TRUE && $vote_dislike_r==FALSE) {
               
              
                   $like_r='<a  type="liked" class="btn btn-warning status_liker_'.$status_reply_id.' liked_r" attr="'.$status_reply_id.'">Liked</a>&nbsp;<span class="label label-info">'.$num_likes_r[0].'</span>';
                 $unlike_r='<a  type="unlike" class="btn btn-danger status_unliker_'.$status_reply_id.' unlike_r" attr="'.$status_reply_id.'">Dislike</a>&nbsp;<span class="label label-info">'.$num_unlikes_r[0].'</span>';
              }
     elseif ($vote_dislike_r==TRUE && $vote_like_r==FALSE) {
                  
             $like_r='<a  type="like" class="btn btn-warning status_liker_'.$status_reply_id.' like_r" attr="'.$status_reply_id.'">Like</a>&nbsp;<span class="label label-info">'.$num_likes_r[0].'</span>';
                 $unlike_r='<a  type="unliked" class="btn  btn-danger status_unliker_'.$status_reply_id.' disliked_r" attr="'.$status_reply_id.'">Disliked</a>&nbsp;<span class="label label-info">'.$num_unlikes_r[0].'</span>';
              }  else {
                 $like_r='<a  type="like" class="btn btn-warning status_liker_'.$status_reply_id.' like_r" attr="'.$status_reply_id.'">Like</a>&nbsp;<span class="label label-info">'.$num_likes_r[0].'</span>';
                 $unlike_r='<a  type="unlike" class="btn btn-danger status_unliker_'.$status_reply_id.' unlike_r" attr="'.$status_reply_id.'">Dislike</a>&nbsp;<span class="label label-info">'.$num_unlikes_r[0].'</span>';
                         
              }
              $pic=$project->viewByUname($reply_author);
                  $uid=$pic['user_id'];
             
               $avatar=$pic['avatar'];
              if ($avatar!=""){
              $feed_r_pic='../user/user/'.$uid.'/'.$avatar;
          }  else {
              $feed_r_pic='img/avatardefault.png';
              }
                     
            if ($reply_author==$_SESSION['uname'] ) {
                       $reply_delete_button='<li><a type="'.$status_reply_id.'" class="btn delete_reply_btn glyphicon glyphicon-trash delete_reply_"'.$status_reply_id.'" title="Delete this comment"> Remove</a></span></li>';
                   } else{
                       $reply_delete_button="";
                   }
                  echo '
                    <div  class="replyboxes pull-left reply_' .$status_reply_id.'">'
                          . 'Reply by:- '
                          . '<a href="home.php?u='.$reply_author. '"><img src="'.$feed_r_pic.'" height="20px" width="20px"> '.$reply_author.'</a>'
                          . '<span class="pull-right">'.$datemade_r 
                           . '<b class="dropdown">
                             <small><span class="btn btn-xs btn-danger dropdown-toggle pull-right" data-toggle="dropdown"  >
                             <span class="glyphicon glyphicon-edit"></span></span>
                            <ul class="dropdown-menu">'.$reply_delete_button
                          . '<li><a class="glyphicon glyphicon-warning-sign" href="report.php?u='.$reply_author.'"> Report</a><li></ul></span>'
                          . '</small></b><br><legend>'.  html_entity_decode($reply_data1).'<br><span class="pull-left spinner_comment'.$status_reply_id.'"></span>'.$like_r.'|'.$unlike_r.'</legend></div>';
                   
                  
                   } 
            echo '<textarea id="reply_textarea_'.$updateid.'" update-detail="'.$updateid.'" class="atwho-inputor status_reply_'.$updateid.' input-custom2" placeholder="comment\'s"></textarea>'
                                . '<span class="pull-left spinner_comment_post'.$updateid.'"></span><button id="reply_butn_'.$updateid.'" attr="'.$updateid.'" type="b" class="btn btn-warning pull-right btn-sm reply_butn reply_'.$updateid.'">Reply</button><span id="status_spinner_r"></span></div></div>';
                               
                                
            }
            
    }           
    }

DB query from classes.php:

    public function totalUpdates($friend,$session, $load) {
        try{
       
       $sql2="SELECT distinct update_id,update_body,time,title,user_id_u,account_name,author,data FROM updates where author in (:friend,:session) order by time desc limit $load,2";
            $stmth=  $this->_db->prepare($sql2);//Check here syntax of $db 
        $stmth->bindValue(":session",$session);
        $stmth->bindValue(":friend",$friend);
        $stmth->execute();
        return $stmth->fetchAll();
        } catch (PDOException $ei){
            echo $ei->getMessage();
        }
    }

i hope some expert who is interested in the problem can share his views and help me solve the javascript bug that keeps on repeatedly producing duplicate values and not fetching all the remaining posts from db.

so far in my trouble shooting i found the ajax to be producing duplicate values is there a way to not let it produce duplicate values.

When you say AJAX is producing duplicate values, have you pinpointed which part of the code is doing this?

@Gandalf no sir i’m not such a javascript expert. i did some googling and tried last() in jquery to get the id value of last div in the loading area and pass it to mysql query but it gives[object object] error. scratching my head. update here of last code i tried in infinite scrolling script.

var sess_uname="<?php echo $session_uname;?>";
     var f_uname="<?php echo htmlspecialchars($_GET['u']);?>";
     var sess_count="<?php echo $total_sess_count;?>";
     var f_count="<?php echo $total_friend_count;?>";
    var funame="<?php echo $f_uname0;?>";
$(".message .status_area").html("<div style='display: flex; justify-content: center;'><h1>Loading Posts...</h1> &nbsp;  "+spinner1+"</div>").show();
   var last= $(" div type").last();
   alert(last[0]);
    if(sess_uname==f_uname){
         $(window).scroll(function(){
              //alert($(window).scrollTop()); 
          // alert($(window).scrollTop()+" "+$(document).height()-$(window).height());
             if($(window).scrollTop()==$(document).height()-$(window).height()){
                 var sub=$(document).height()-$(window).height();
      //lert(sub);
           // alert($(window).scrollTop()+"  "+sub); 
            load++;
     // alert(load+" "+sess_count);
             if(load * 2 < sess_count){
                 $(".message").html("<h1>no more posts to show </h1>");
             }else{
      
                 $.post("st&com.php", {"load":load,"sess_count":sess_count},function(data){
        $(".message").html(spinner1).show();         
        $("#status_area").append(data);
                    $(".hide").hide();
        $(".message").html(spinner1).hide();            
  
    });
             }
             }
         });
     }else {
         $(window).scroll(function(){
           
             if($(window).scrollTop()==$(document).height()-$(window).height()){
             load++;
   // alert($(window).scrollTop()+"  "+$(document).height()-$(window).height());
             if(load *2 >f_count){
                 $(".message").html("<h1>no more posts to show here</h1>");
             }else{
                
                 $.post("status_list.php", {funame:funame, load:load},function(data){
        $(".message").html(spinner1).show();         
        $("#status_area").append(data);
                    $(".hide").hide();
        $(".message").html(spinner1).hide();            
        
                 });
             }
             }
         });    
     }

mysql query in php:

 public function totalUpdates($friend,$session,$update_id, $load) {
    try{
   // $sql2="SELECT distinct update_id,update_body,time,title,user_id_u,account_name,author,data FROM updates WHERE author=:friend and account_name=:session order by time desc limit $load,2";
   $sql2="SELECT distinct update_id,update_body,time,title,user_id_u,account_name,author,data FROM updates where author in (:friend,:session) and update_id > :update_id order by time desc limit $load,2";
        $stmth=  $this->_db->prepare($sql2);//Check here syntax of $db 
    $stmth->bindValue(":session",$session);
    $stmth->bindValue(":friend",$friend);
    $stmth->bindValue(":update_id",$update_id);
    $stmth->execute();
    return $stmth->fetchAll();
    } catch (PDOException $ei){
        echo $ei->getMessage();
    }
}

changes in st&com php script:

   $f = array();
  $ids=  array();
$stmt=  $conn->prepare("select friend_one, friend_two from friends where (friend_one=:session OR friend_two=:session) and (friend_one>=:session or friend_two>=:session) and accepted='1'");
$stmt->bindparam(":session",$_SESSION['uname']);
$stmt->execute();
$f=$stmt->fetchAll();
$f_count=count($f);

$ids=  ff($f, $project);
$i=0;
//foreach ($ids as $i=>$v){
// while($i<$f_count){    
$id=$v;

//fetch username from update table in db and inject it to the feed query.
   $imp_id= implode(',', $ids);
//$id1=$ids[$i];

$totalUpdates=$project->totalUpdates($imp_id,$_SESSION['uname'] ,$update_id,$load);   
  $i++;
 
    /*

     *we get the $sess_count and $load from javascript in home page and forward the logic if load*2 is greater than 
     * $sess_count variable if it is great then the $total_sess_count is set to 0 else it is fetched from classes.inc.php 
     *     
     */
    
    if($load*2>$sess_count){
        $total_sess_count=0;
    }
 else {
    
  $total_sess_count=$project->totalupdatescount($id);
 }

................

Just looking real quick my guess is the Event used.

i.e. the page gets a scroll, an added element changes the height triggering a scroll event. ↶

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.