php - 新条目后 AJAX 分页无法正常工作

标签 php jquery mysql ajax

我有一个主页“landing.php”,在一个 div 中,我使用 ajax 函数“fetch_pages.php”调用另一个页面。在 fetch_pages.php 中,我一次从 db 加载数据作为 5 条记录,当用户到达页面末尾时,将显示接下来的 5 条记录。一切正常。

但在landing.php中,当我输入一条新记录并重新加载div时,div内容变为空白,不显示最新内容,手动刷新整个页面后再次显示所有记录。不明白哪里出了问题,请帮忙。

landing.php页面

        <div class="mainsection">
          <div>
             <div class="pull-left postimage"><?php echo "<img src=profile_pic/".$ProfilePic ." />"; ?></div>
        <div class="pull-left posttext">
            <div class="postname"><?php echo $Name; ?></div>
            <p><?php echo $UT." - ".$Designation." - ".$Company; ?></p></div>
            <textarea id="posting" name="posting" rows="2" cols="50" placeholder="Share something here..."></textarea>
        <div class="clear"></div>
        <hr>
      </div>
      <div class="fileUpload btn btn-default">
          <span><i class="fa fa-camera-retro" style="margin-right: 6px;" aria-hidden="true"></i>Upload Image</span>
          <input type="file" class="upload" />
      </div>
      <div>
          <input class="postall btn btn-primary pull-right" type="submit" onClick="UserPost()" value="Post">
      </div>
      <div class="clear"></div>
    </div>

    <!-- Loading User Posts -->
    <div id="mainsectionID">
        <div id="results"><!-- results appear here as list --></div>
    </div>

   <script>
    (function($){   
$.fn.loaddata = function(options) {// Settings
    var settings = $.extend({ 
        loading_gif_url : "images/ajax-loader.gif", //url to loading gif
        end_record_text : 'No more records found!', //no more records to load
        data_url        : 'fetch_pages.php', //url to PHP page
        start_page      : 1 //initial page
    }, options);

    var el = this;  
    loading  = false; 
    end_record = false;
    contents(el, settings); //initial data load

    $(window).scroll(function() { //detact scroll
        if($(window).scrollTop() + $(window).height() >= $(document).height()){ //scrolled to bottom of the page
            contents(el, settings); //load content chunk 
        }
    });     
}; 
//Ajax load function
function contents(el, settings){
    var load_img = $('<img/>').attr('src',settings.loading_gif_url).addClass('loading-image'); //create load image
    var record_end_txt = $('<div/>').text(settings.end_record_text).addClass('end-record-info'); //end record text

    if(loading == false && end_record == false){
        loading = true; //set loading flag on
        el.append(load_img); //append loading image
        $.post( settings.data_url, {'page': settings.start_page}, function(data){ //jQuery Ajax post
            if(data.trim().length == 0){ //no more records
                el.append(record_end_txt); //show end record text
                load_img.remove(); //remove loading img
                end_record = true; //set end record flag on
                return; //exit
            }
            loading = false;  //set loading flag off
            load_img.remove(); //remove loading img 
            el.append(data);  //append content 
            settings.start_page ++; //page increment
        })
    }
}

})(jQuery);

$("#results").loaddata(); //load the results into element
    </script>

fetch_pages.php 代码-

<?php
session_start();
include 'db.php'; //include config file

$UserID=$_SESSION['uid'];
$UserType=$_SESSION['utype'];

$GLOBALS['lks']=0;
$GLOBALS['cmnts']=0;
$GLOBALS['disabled']="";

//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);

//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
header('HTTP/1.1 500 Invalid page number!');
exit();
}

//get current starting point of records
$position = (($page_number-1) * $item_per_page);
?>
<!---post start -->
<?php
//fetch records using page position and item per page. 
$results = $linkID1->query("select slno,posts,img_link,video_link,likes,comments,shares,post_date,post_time,UserID from user_posts where UserID='$UserID' or UserID in(select MyFriendsUserID from user_connections where MyUserID='$UserID') or UserID in(select MyUserID from user_connections where MyFriendsUserID='$UserID') order by slno desc LIMIT $position, $item_per_page")
or

die(mysqli_error());

//output results from database
?>

<?php
while($row = mysqli_fetch_array($results))
{ //fetch values
                    $CUID=$row['UserID'];

                    $stmt = $linkID1->prepare("select Name,Company,Designation,UserType from user_details where UserID=?");
                    $stmt->bind_param("s", $CUID);
                    $stmt->execute();
                    $stmt->bind_result($Name2,$Company2,$Designation2,$UType);
                    $stmt->fetch();
                    $stmt->close();

                    $UT2='';
                    if($UType=='A')
                    {
                        $UT2='Advertiser';
                    }
                    else if($UType=='P')
                    {
                        $UT2='Publisher';
                    }

                    $stmt = $linkID1->prepare("select ProfilePic from user_picture where UserID=?");
                    $stmt->bind_param("s", $CUID);
                    $stmt->execute();
                    $stmt->bind_result($PPic);
                    $stmt->fetch();
                    $stmt->close();
        ?>
            <div class="mainsection">
          <div>
            <div class="pull-left postimage"><?php echo "<img src=profile_pic/".$PPic ." />"; ?></div>
            <div class="pull-left posttext">
                <div class="postname"><?php echo $Name2; ?></div>
                <p><?php echo $UT2." - ".$Designation2." - ".$Company2; ?></p></div>
            <div class="clear"></div>
            <div class="postdowntxt"><p><?php echo $row['posts']; ?></p></div>
            <hr>
          </div>
          <div class="btnclasess" id="likescommentID<?php echo $row[slno]; ?>">
              <div class="likescomment"><?php dataLC($linkID1, $row['slno'],$CUID); ?><a style="padding-right: 7px" href="#"><?php if($GLOBALS['lks']==0){echo '';}else{ echo $GLOBALS['lks']." Likes"; } ?></a><a href="#"><?php if($GLOBALS['cmnts']==0){echo '';}else{ echo $GLOBALS['cmnts']." Comments"; } ?></a></div>
             <div class="pull-left likebtn"><button <?php echo $disabled; ?> class="btn" id="likeButton<?php echo $row[slno]; ?>" onClick="connect(<?php echo $row[slno]; ?>)"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</button></div>
             <button class="pull-left btnhideshow show_hide" data-toggle="collapse" data-target="#demo<?php echo $row['slno']; ?>"><li class="fa fa-comments show_hide" style="margin-right: 6px;"></li>Comment</button>
             <button class="pull-left btnhideshow show_hide"><li class="fa fa-share-alt show_hide" style="margin-right: 6px;"></li>Share</button>
             <div class="clear"></div>
          <div class="clear"></div>
        </div>

        <!-- Display All Comments -->
        <div id="myModal<?php echo $row['slno']; ?>" class="modal">
        <div id="DialogDiv<?php echo $row['slno']; ?>">
          <!-- Modal content -->
          <div class="modal-content" id="modalDialog<?php echo $row['slno']; ?>">

            <p class="popupheading"><?php if($GLOBALS['cmnts']==0){echo '';}else{ echo $GLOBALS['cmnts']." Comments"; } ?></p> 
            <?php
            $result2 = $linkID1->query("select upc.slno,upc.Comment,upc.CommentedUserID,up.ProfilePic from user_posts_comments upc join user_picture up on upc.CommentedUserID=up.UserID where PostID='$row[slno]' order by upc.slno")
            or
            die(mysqli_error());

            while($row2 = mysqli_fetch_array($result2))
            {
        ?>
                <div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row2['ProfilePic']." />"; ?></div>
                           <div class="pull-right commentextstyle commentandreply">
                             <?php echo $row2['Comment']; ?>
                           </div>
                           <div class="pull-left likebtn"><a href="#" onClick="return false;" data-toggle="collapse" data-target="#nReply2<?php echo $row2['slno']; ?>"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</a></div>
                           <!--<div class="pull-left likebtn"><a href="#"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</a></div>-->
                           <div class="clear"></div>
                           <div id="nReply2<?php echo $row2['slno']; ?>" class="collapse">
                    <div>
                     <input class="replybox" type="text" id="nReplyBox2<?php echo $row2['slno']; ?>" onkeyup="enter_reply2(<?php echo $row2['slno']; ?>,<?php echo $CUID; ?>,<?php echo $row['slno']; ?>);">
                    </div>
                  </div>

                  <div class="clear"></div>

                   <!-- Nested Comments Starts -->
                   <div id="NestedCmntsDialog" class="nestedcmnts">
                   <?php
                    $result3 = $linkID1->query("select upcr.slno,upcr.PostID,upcr.ReplyTo,upcr.ReplyBy,upcr.Comments,up.ProfilePic from user_posts_comments_reply upcr join user_picture up on upcr.ReplyBy=up.UserID where upcr.PostID='$row2[slno]' and (upcr.ReplyTo='$row2[CommentedUserID]' or upcr.ReplyBy='$row2[CommentedUserID]') order by upcr.slno")
                    or
                    die(mysqli_error());

                    while($row3 = mysqli_fetch_array($result3))
                    {
                 ?>
                   <div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row3['ProfilePic']." />"; ?></div>
                   <div class="pull-right commentextstyle commentandreply">
                     <?php echo $row3['Comments']; ?>
                   </div>
                   <div class="pull-left likebtn"><a href="#" onClick="return false;" data-toggle="collapse" data-target="#nReply2<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</a></div>
                   <div class="clear"></div>
                   <div id="nReply2<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" class="collapse">
                    <div>
                     <input class="replybox" type="text" id="nReplyBox2<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" onkeyup="enter_nested_reply2(<?php echo $row3['slno']; ?>,<?php echo $row3['ReplyBy']; ?>,<?php echo $row['slno']; ?>,<?php echo $row3['PostID']; ?>);">
                    </div>
                  </div>
                   <!--<div class="pull-left likebtn"><a href="#"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</a></div>-->
                   <div class="clear"></div>

                 <?php
                    }
                 ?>
                 </div>
                   <!-- Nested Comments Ends -->
        <?php
            }
        ?>
            <div class="invidone"><a href="#" class="close" id="close3">Close</a></div>
          </div>
          </div>
        </div>
        <!-- Display All Comments -->

              <div class="slidingDiv collapse" id="demo<?php echo $row['slno']; ?>">
                <div class="viewallcomments"><a href="#" id="myBtn2" onClick="LoadComment(<?php echo $row[slno]; ?>); return false;">View All Comments</a></div>
                 <div class="allcomment" id="commentsLoad<?php echo $row['slno']; ?>">
                 <?php
                    $result2 = $linkID1->query("select upc.slno,upc.Comment,upc.CommentedUserID,up.ProfilePic from user_posts_comments upc join user_picture up on upc.CommentedUserID=up.UserID where upc.PostID='$row[slno]' order by upc.slno desc limit 3")
                    or
                    die(mysqli_error());

                    while($row2 = mysqli_fetch_array($result2))
                    {
                 ?>
                 <!-- Showing Top 3 Comments -->
                 <div id="nestedReplyDiv<?php echo $row['slno']; ?>">
                   <div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row2['ProfilePic']." />"; ?></div>
                   <div class="pull-right commentextstyle commentandreply">
                     <?php echo $row2['Comment']; ?>
                   </div>
                   <div class="pull-left likebtn"><a href="#" onClick="return false;" data-toggle="collapse" data-target="#nReply<?php echo $row2['slno']; ?>"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</a></div>
                   <div class="clear"></div>
                   <div id="nReply<?php echo $row2['slno']; ?>" class="collapse">
                    <div>
                     <input class="replybox" type="text" id="nReplyBox<?php echo $row2['slno']; ?>" onkeyup="enter_reply(<?php echo $row2['slno']; ?>,<?php echo $CUID; ?>);">
                    </div>
                  </div>
                   <!--<div class="pull-left likebtn"><a href="#"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</a></div>-->
                   <div class="clear"></div>

                   <!-- Nested Comments Starts -->
                   <div id="NestedCmnts" class="nestedcmnts">
                   <?php
                    $result3 = $linkID1->query("select upcr.slno,upcr.PostID,upcr.ReplyTo,upcr.ReplyBy,upcr.Comments,up.ProfilePic from user_posts_comments_reply upcr join user_picture up on upcr.ReplyBy=up.UserID where upcr.PostID='$row2[slno]' and (upcr.ReplyTo='$row2[CommentedUserID]' or upcr.ReplyBy='$row2[CommentedUserID]') order by upcr.slno")
                    or
                    die(mysqli_error());

                    while($row3 = mysqli_fetch_array($result3))
                    {
                 ?>
                   <div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row3['ProfilePic']." />"; ?></div>
                   <div class="pull-right commentextstyle commentandreply">
                     <?php echo $row3['Comments']; ?>
                   </div>
                   <div class="pull-left likebtn"><a href="#" onClick="return false;" data-toggle="collapse" data-target="#nReply<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</a></div>
                   <div class="clear"></div>
                   <div id="nReply<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" class="collapse">
                    <div>
                     <input class="replybox" type="text" id="nReplyBox<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" onkeyup="enter_nested_reply(<?php echo $row3['slno']; ?>,<?php echo $row3['ReplyBy']; ?>,<?php echo $row['slno']; ?>,<?php echo $row3['PostID']; ?>);">
                    </div>
                  </div>
                   <!--<div class="pull-left likebtn"><a href="#"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</a></div>-->
                   <div class="clear"></div>

                 <?php
                    }
                 ?>
                 </div>
                   <!-- Nested Comments Ends -->
                 </div>
                 <?php
                    }
                 ?>
                 </div>

                  <textarea id="commentarea<?php echo $row[slno]; ?>" class="secondtextareay pull-left" rows="2" cols="50" placeholder="Post comments here..." onkeyup="enter_comment(<?php echo $row['slno']; ?>,<?php echo $CUID; ?>);"></textarea>
                   <!--<div class="fileUpload second_fileupload btn btn-default pull-left">
                    <span><i class="fa fa-camera-retro" style="margin-right: 6px;" aria-hidden="true"></i></span>
                    <input type="file" class="upload" />
                  </div>-->
                  <div class="clear"></div>
             </div>
             </div>
        <?php
}
?>
<!--post end-->

<?php 
    function dataLC($linkID1, $val, $CUID)
    {
        $UserID=$CUID;
        $LgUserID=$_SESSION['uid'];

        $stmt = $linkID1->prepare("select likes,comments from user_posts where slno=?");
        $stmt->bind_param("s", $val);
        $stmt->execute();
        $stmt->bind_result($lksD,$cmntsD);
        $stmt->fetch();
        $stmt->close();

        $GLOBALS['lks']=$lksD;
        $GLOBALS['cmnts']=$cmntsD;

        $stmt = $linkID1->prepare("select count(slno) from user_posts_likes where MyUserID=? and FrUserID=? and PostID=?");
        $stmt->bind_param("sss", $UserID,$UserID,$val);
        $stmt->execute();
        $stmt->bind_result($cnt);
        $stmt->fetch();
        $stmt->close();

        if($cnt>=1)
        {
            $GLOBALS['disabled']="disabled";
        }
        else
        {
            $GLOBALS['disabled']="enabled";
        }

        $stmt = $linkID1->prepare("select count(slno) from user_posts_likes where MyUserID=? and FrUserID=? and PostID=?");
        $stmt->bind_param("sss", $UserID,$LgUserID,$val);
        $stmt->execute();
        $stmt->bind_result($cnt2);
        $stmt->fetch();
        $stmt->close();

        if($cnt2>=1)
        {
            $GLOBALS['disabled']="disabled";
        }
        else
        {
            $GLOBALS['disabled']="enabled";
        }

        $stmt = $linkID1->prepare("select count(slno) from user_posts_likes where MyUserID=? and FrUserID=? and PostID=?");
        $stmt->bind_param("sss", $LgUserID,$UserID,$val);
        $stmt->execute();
        $stmt->bind_result($cnt3);
        $stmt->fetch();
        $stmt->close();

        if($cnt3>=1)
        {
            $GLOBALS['disabled']="disabled";
        }
        else
        {
            $GLOBALS['disabled']="enabled";
        }
    }
?>

<script>
        $('.btn').on('click', function(e) 
        { 
            $(this).prop('disabled',true); });
    </script>

    <script>
        function UserPost() {
        var x = document.getElementById('posting').value;

        var timezone_offset_minutes = new Date().getTimezoneOffset();
        timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;

        $.ajax({
        type: "POST",
        url: "user-post.php?p="+x+"&tz="+timezone_offset_minutes,
        success: function(data) {
            $("#mainsectionID").load(" #mainsectionID");
            document.getElementById('posting').value='';
        }
        });
        }
    </script>

    <script type="text/javascript">
    function connect(num) {
        $.ajax({
        type: "POST",
        url: "user-likes.php?id="+num,
        success: function(data) {
            if(data=='1')
            {
                $("#likescommentID"+num).load(" #likescommentID"+num);
            }
        }
        });
        }

    function enter_comment(postid,userpostedid) {
           if (event.keyCode == 13 && event.shiftKey) {
               // shift+enter pressed
             }
             else if(event.keyCode == 13){
                      //enter key pressed
                      var cmnt = document.getElementById('commentarea'+postid).value;
                      $.ajax({
                        type: "POST",
                        url: "user-comments.php?id="+postid+"&cmnt="+cmnt,
                        success: function(data2) {
                            if(data2=='1')
                            {
                                $("#commentsLoad"+postid).load(" #commentsLoad"+postid);
                                $("#likescommentID"+postid).load(" #likescommentID"+postid);
                            }
                        }
                        });
                      document.getElementById('commentarea'+postid).value='';
            }
            else{
                //nothing
            }
    }
    </script>

    <script type="text/javascript">
    function enter_reply(slno,userpostedid) {
           if (event.keyCode == 13 && event.shiftKey) {
               // shift+enter pressed
             }
             else if(event.keyCode == 13){
                      //enter key pressed
                      var cmnt = document.getElementById('nReplyBox'+slno).value;
                      $.ajax({
                        type: "POST",
                        url: "user-comments-reply.php?id="+slno+"&cmnt="+cmnt,
                        success: function(data2) {
                            if(data2=='1')
                            {
                                $("#commentsLoad"+slno).load(" #commentsLoad"+slno);
                            }
                        }
                        });
                      document.getElementById('nReplyBox'+slno).value='';
            }
            else{
                //nothing
            }
    }


    function enter_reply2(slno,userpostedid,dno) {
           if (event.keyCode == 13 && event.shiftKey) {
               // shift+enter pressed
             }
             else if(event.keyCode == 13){
                      //enter key pressed
                      var cmnt = document.getElementById('nReplyBox2'+slno).value;
                      $.ajax({
                        type: "POST",
                        url: "user-comments-reply.php?id="+slno+"&cmnt="+cmnt,
                        success: function(data2) {
                            if(data2=='1')
                            {

                                $("#DialogDiv"+dno).load(" #DialogDiv"+dno);
                                //$("#modalDialog"+dno).load(" #modalDialog"+dno);
                            }
                        }
                        });
                      document.getElementById('nReplyBox2'+slno).value='';
            }
            else{
                //nothing
            }
    }
    </script>

    <script type="text/javascript">
    function enter_nested_reply(slno,userpostedid,divNo,pid) {
           if (event.keyCode == 13 && event.shiftKey) {
               // shift+enter pressed
             }
             else if(event.keyCode == 13){
                      //enter key pressed
                      var tot=(slno*slno)+pid;
                      var cmnt = document.getElementById('nReplyBox'+tot).value;

                      $.ajax({
                        type: "POST",
                        url: "user-comments-reply-nested.php?id="+slno+"&cmnt="+cmnt+"&upid="+userpostedid,
                        success: function(data2) {
                            if(data2=='1')
                            {
                                $("#nestedReplyDiv"+divNo).load(" #nestedReplyDiv"+divNo);
                            }
                        }
                        });
                      document.getElementById('nReplyBox'+tot).value='';
            }
            else{
                //nothing
            }
    }


    function enter_nested_reply2(slno,userpostedid,divNo,pid) {
           if (event.keyCode == 13 && event.shiftKey) {
               // shift+enter pressed
             }
             else if(event.keyCode == 13){
                      //enter key pressed
                      var tot=(slno*slno)+pid;
                      var cmnt = document.getElementById('nReplyBox2'+tot).value;

                      $.ajax({
                        type: "POST",
                        url: "user-comments-reply-nested.php?id="+slno+"&cmnt="+cmnt+"&upid="+userpostedid,
                        success: function(data2) {
                            if(data2=='1')
                            {
                                $("#DialogDiv"+divNo).load(" #DialogDiv"+divNo);
                                //$("#modalDialog"+divNo).load(" #modalDialog"+divNo);
                            }
                        }
                        });
                      document.getElementById('nReplyBox2'+tot).value='';
            }
            else{
                //nothing
            }
    }
    </script>

    <script>

    function LoadComment(num) {
        var modal2 = document.getElementById('myModal'+num);
        var span2 = document.getElementById("close3");

        span2.onclick = function() {
                modal2.style.display = "none";
            }

        window.onclick = function(event) {
                if (event.target == modal2) {
                    modal2.style.display = "none";
                }
            }

        var x = document.getElementById('myBtn2');
        modal2.style.display = "block";
        }
    </script>

最佳答案

问题已解决。在ajax的success方法中再次调用了分页。

关于php - 新条目后 AJAX 分页无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47412742/

相关文章:

php - 如何删除成员(member)A在聊天中接收和发送的消息而不删除成员(member)B帐户中的消息

MySql 删除行并将其添加到另一个表?

php - Delphi CryptoBlackBox 和 PHP

php - 从 3 个字段中选择,第 0 行唯一 ID,第 1 行多个 ID 号,第 2 行一个字母 int(1) 到新数组中

javascript - Chart.js 数据集 Controller 'null' 绘制图表时

jquery - jscrollpane 在 firefox 中不起作用,在 chrome 中起作用

php - 在mysql中搜索关键字并获取至少有5个关键字的数据

php - 在 PHP 中从 SQL 表获取单个结果

php - 当 memory_limit 设置为 -1 时,什么限制了 PHP 内存?

javascript - Bootstrap : Creating Multiple Popovers with Button click