0

I have a chat program which uses ajax to run a php script to query a MYSQL DB, pulls the chat details and provides it to javascript which then pushes it to a div.

At present, the data appears at the top of the div and works it's way down, and the goal is to have the latest comment to appear from the bottom working its way up the screen.

Current code snippets:

AJAX:

function displayChat() {

        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 (this.readyState == 4 && this.status == 200) {
                document.getElementById("chat").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET","displayChat.php?",true);
        xmlhttp.send();

    }

HTML Chat DIV

<div id="chat"></div>

PHP code

$displayChat =mysql_query(
     "select c.userID, u.userName, c.comments, c.datetime, c.tag
     from chat c
     inner join userAccounts u
     on u.userID=c.userID
     order by c.datetime ASC",
    $connection);

while ($row = mysql_fetch_assoc($displayChat )) {
    echo "(".$row['datetime'].")"." <b>".$row['userName']."</b>: ".$row['comments']."<br>";
}

CSS

#chat {

    height: 90%;
    overflow-y: scroll;     
    background-color: white;
    text-align: left;
    padding-left: 25px;
    bottom: 0;

}

How can I achieve this?

cweiske
  • 30,033
  • 14
  • 133
  • 194
Brad
  • 25
  • 3
  • this might help: http://stackoverflow.com/questions/585945/how-to-align-content-of-a-div-to-the-bottom – Jeff Jan 18 '17 at 23:20

2 Answers2

0
var current = document.getElementById("chat").innerHTML;
current.innerHTML = current.innerHTML + this.responseText;

How about adding that to your onreadystatechange AJAX function?

0

I think this is what you are searching for:

// html
<div id="chat-wrapper">
    <div id="chat-content">

        text1<br>
        text2<br>
    </div>
</div>

// CSS
#chat-wrapper {
    border: 1px #ededed solid;
    height: 200px;
    overflow-y: scroll;     
    background-color: white;
    text-align: left;
    position: relative;
}

#chat-content {
    position: absolute;
    bottom: 0;
    left: 0;
    padding-left: 25px;
}

then of course you need to change this

document.getElementById("chat").innerHTML = this.responseText;

to

document.getElementById("chat-content").innerHTML = this.responseText;

It would be better to only send the newly added messages from server to client, otherwise you could end up with tons of messages. But that would need some more work. (saving latest trasmitted msg on client, add that timestamp to request, ...)

Jeff
  • 6,895
  • 1
  • 15
  • 33