I am trying to make a jquery/php chat and i append data to the chat box, but then when the jquery loop trys to get the .last() data it gets the one before the appended data causing it to append the same data over and over again. hHow would i get the .last() div added even if its appended?

<script type="text/javascript" charset="utf-8">
    function addmsg(type, msg){
        /* Simple helper to add a div.
        type is the name of a CSS class (old/new/error).
        msg is the contents of the div */
        $("#messages").append(
            "<div class='msg "+ type +"'>"+ msg +"</div>"
        );
    }

    function waitForMsg(){
        /* This requests the url "msgsrv.php"
        When it complete (or errors)*/
        var className = $('.messages:last-child').attr('class');
        $.ajax({
            type: "GET",
            url: "msgsrv.php?ID=11&MID=409&SELECT=" + className,

            async: true, /* If set to non-async, browser shows page as "Loading.."*/
            cache: false,
            timeout:50000, /* Timeout in ms */

            success: function(data){ /* called when request to barge.php completes */
                addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
                setTimeout(
                    waitForMsg, /* Request next message */
                    1000 /* ..after 1 seconds */
                );
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                addmsg("error", textStatus + " (" + errorThrown + ")");
                setTimeout(
                    waitForMsg, /* Try again after.. */
                    15000); /* milliseconds (15seconds) */
            }
        });
    };

    $(document).ready(function(){
        waitForMsg(); /* Start the inital request */
    });
    </script>

    <div id="chat" style="overflow:auto;">
        <div id="messages" class="0" style="display:inline;">
        </div>
        <div id="messages" class="0" style="display:inline;">
        </div>
    </div>

Dani AI

Generated

Brief diagnosis and recommended pattern. The thread shows the usual culprits: duplicate container IDs (as noted), mismatched selector usage (as flagged), and unexpected server output (a stray HTML fragment or whitespace can make the client think the last message didn’t change). Relying on DOM queries alone to discover “the newest” message is fragile when polling races with append operations or when the server returns extra bytes. A reliable approach is to track the last message ID on the client and ask the server for only messages with id > lastID.

Example polling pattern (server returns JSON array of {id,text}):

var lastID = 0;
function poll() {
  $.getJSON('msgsrv.php', {ID:11, MID:409, last:lastID})
    .done(function(messages) {
      messages.forEach(function(m) {
        var node = $('<div>').addClass('msg').attr('data-id', m.id).text(m.text);
        $('#messages').append(node);
        if (m.id > lastID) lastID = m.id;
      });
      setTimeout(poll, 1000);
    })
    .fail(function(){ setTimeout(poll, 15000); });
}
$(poll);

Practical notes and fixes: select the last element with explicit selectors (for example $('#messages .msg').last() or $('#messages').children().last()), but prefer the data-id/lastID approach so the server drive determines “newer” messages. Create nodes with jQuery methods (not raw concatenated HTML) to avoid timing and XSS issues; update lastID immediately after inserting each message; keep the scroll position in sync if needed.

Troubleshooting checklist: ensure a single #messages container, validate server output (no stray <br>, whitespace or UTF-8 BOM), send JSON with an appropriate Content-Type, and avoid closing PHP tags that can inject accidental whitespace. For a real-time chat with many users, consider WebSockets or Server-Sent Events instead of short polling.

Recommended Answers

All 6 Replies

Without looking at the js first things I see are 2 ids called "messages" each with display:inline.

Yeah and i want to select the .last() messages

IDs can only appear once.

Your code references #messages (an id) and also .messages (a class) - which is it to be?

Your js results with the ajax call query string having SELECT=undefined

I want it to say that the id is messages then the class will have the message so .1 .2 .3 ...... .10 etc and then it needs to get the id from #messages and then check the database, and then it'll append the newer ones and then jquery will have to get the id from the newset appeneded #messages and check again.

For starts I see at line 14:

$('.messages:last-child')

But in your HTML I don't see anything with a classname of "messages". Should that dot not be a hashtag? In line 14?

From a second look at it I would suspect that the error lies in your PHP file. Does it get the required data passed to it? Does
url: "msgsrv.php?ID=11&MID=409&SELECT=" + className,
not always send the same request? For ID=11 and MID=409?

I got it to work. I had to switch

$("#messages").append(
    "<div class='msg "+ type +"'>"+ msg +"</div>"
);

to

$("#chat").append(
    msg
);

and i forgot to show my scond file but i had a <br> at the end which messed it up so i had to move it to the beggining.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.