简体   繁体   中英

How can I stop changes in scroll position when refreshing php?

I'm trying to load my php code from a database without refreshing, using the ajax.load() function, into a 'text' div that acts as a messaging box with an overflow of scroll. However, whenever the reload occurs, the entire div scrolls back to the top, making it impossible to back through the history of the messages. I'm looking for a way to either A) prevent this scroll from happening or B) change it so it only updates when new information is added to the database, not on a set interval. I've tried using scroll top but it doesn't seem to work. The echo will output the scroll position correctly, but it won't work to set the scroll.

$(document).ready(function() { 
setInterval(function () {
    var loc = $('#".$recipient." > .text').scrollTop();
    console.log(loc);
    $('#".$recipient."').load('update.inc.php', {
            roomID: ".$roomID.",
            recip: '".$recName."'
        });
    $('.text').scrollTop(loc);
    }, 1000);
});

My PHP update code is this:

<?php
include("dbh.inc.php");
session_start();

$roomID = $_POST['roomID'];
$recName = $_POST['recip'];

echo "<div class = 'info'>";
echo "<a href = 'social.php'><i class='fas fa-long-arrow-alt-left'></i></a>";
echo "<div class = 'recipient-info'>";
echo "<div class = 'user-img'></div>";
echo "<h4 class = 'username'>".$recName."</h4>";
echo "</div>"; //End recipient-info
echo "</div>"; //End info
echo "<div class = 'text'>";

$getMessages = "SELECT * FROM chatroom_posts WHERE roomId = '$roomID' ORDER BY postTime ASC";
$messages=$conn->query($getMessages);
if($messages->num_rows > 0) {
    while($message=$messages->fetch_assoc()) {
        if($message['userId']==$_SESSION['uid']) {
            echo "<p class = 'to'>".$message['content']."</p>";
        } else {
            echo "<p class = 'from'>".$message['content']."</p>";
        }
    }
} else {
    echo "<p class ='from'>You haven't yet talked to me! Enter a message to get started!</p>";
}
echo "</div>"; //End text

Right well, as for the scrolling bit, using JQuery you might want to use the animate method, to move the scroll window.

As for you idea to only add new updates... that would be ideal. Here are some places to start.

  • You need to revise your query and markup, server side, to respond with only new messages, messages after a certain time / or return JSON, so you can filter and render it client side.

  • If you are going to append only the new messages to the DOM, it would be best if your server only responded with that markup. Otherwise you will need to parse the HTML client side to get just the new content.

As for updating with an "append" or "prepend" the new content to the DOM, you can use jQuery's append/prepend methods

The load method, provides a little bit of a shorthand for "load this content, and replace the contents of x", if you want to stick with load, You can do something like

$("#messages-list").append($("<div>").load('update.inc.php', {...}).html());

It is, not particularly elegant and perhaps wastful, a cleaner, and perhaps more explicit solution would be

$.ajax({ type: "GET",   
     url: "update.inc.php",   
     success : function(messages)
     {
         $('#messages-list').append(messages);
     }
});

Also, your setInterval may be a tad bit aggressive, polling your server every second, can be rough, with one user maybe not, but as the number of sessions grows, you will begin bombarding not just your HTTP server, but your SQL server as well. 5, 10 even 30 second intervals, would be fine.

You could even play with the polling delay, dynamically setting it to 30 seconds, then after a message is sent by the user, lessen the delay to every 5 seconds, then after 1 min of no activity, set it back to 30 or even 60 seconds...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM