Govind Rai
Govind Rai

Reputation: 15828

Lag for just part of AJAX response

I made a simple chat. It's working properly, but not behaving as expected. When a user submits a message, the user's name, time and message are supposed to display.

It so happens that the username and response appear first and the time seems to be inserting itself after a slight delay (that's the lag). I can't figure out why, especially since the response is (or at least seems to be) sent as a whole and nothing is being inserting once the response is sent from the server...

Here's the link to the chat. You can input dummy username and dummy messages.

And here are the important pieces of code:

PHP

while ($row = $result->fetch_assoc()) {
        $time = date('g:ia', $row['time']);
        echo "<p class=\"message\"><i>{$row['username']}</i> ($time): {$row['content']}</p>";
    }

JavaScript

ajax.onreadystatechange = function () {
    if (ajax.status === 200 && ajax.readyState === 4) {
        document.getElementById('messagesArea').innerHTML = ajax.responseText;
    }
};

Upvotes: 0

Views: 103

Answers (1)

tyteen4a03
tyteen4a03

Reputation: 1932

Your culprit is this section of the script:

var content = document.getElementById('messageBox').value;

if ( content === '') {
    return;
} else {
    var ajax = new XMLHttpRequest();
    var username = document.getElementById('signedin').innerHTML;

    document.getElementById('messageBox').value = '';

    ajax.open('POST', 'postmessage.php', true);
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajax.onreadystatechange = function () {
        if (ajax.status === 200 && ajax.readyState === 4) {

            // if there are errors echoed from the PHP file
            if (ajax.responseText != "") {
                document.getElementById('mysqliError').innerHTML = ajax.responseText;
                return;
            }

            document.getElementById('messagesArea').insertAdjacentHTML('beforeend', '<p class="message"><i>' + username + '</i>: ' + content + '</p>');
        }
    };
    ajax.send('username=' + username + '&content=' + content);
}

Notice this line: document.getElementById('messagesArea').insertAdjacentHTML('beforeend', '<p class="message"><i>' + username + '</i>: ' + content + '</p>');

You are inserting the message, without the time, into #messagesArea. Then, in getRecentMessages later, it is set to fetch the entire chat log from displaymessages.php and overwrite #messagesArea with the content of the output, which does have the time.

Upvotes: 1

Related Questions