joergi1988
joergi1988

Reputation: 73

Jquery Chat - show the new messages

I have make a Chat with php and jquery.

It works fine but i have a little problem:

i load the Messages every 5 sec, but i load all and than it scrolls to bottom.

How can i change this to load only new messages:

Thats the jquery in index:

    function LoadChatVerlauf() {

                    $('.messages').empty();

    $.getJSON('infos.php', {'getchat':1 }, function(data) {

                for(var key in data) {
                    var classe = '';


                    if(data[key].chat_username == '<?php echo $user; ?>') {
                        classe = 'i';
                    } else {
                        classe = 'friend-with-a-SVAGina';
                    }

                        $('.messages').append('<li class="'+classe+'"><div class="head"><span class="time">'+data[key].chat_time+', '+data[key].chat_date+' </span><span class="name">'+data[key].chat_user+'</span></div><div class="message">'+data[key].chat_nachricht+'</div></li>');

                    }

            })//.fail(function() { alert('Unable to fetch data, please try again later.') });


        BOTTOM();

    }   

thats the php file:

if(isset($_GET['getchat'])){


    $array = array();


    $sql = "SELECT user, username, nachricht, date, time FROM chat_verlauf ORDER BY date, time LIMIT 60";

    $res = mysqli_query($db, $sql);

    if(mysqli_num_rows($res) > 0) {

        while($ds = mysqli_fetch_object($res))
        {
            $time = date("H:i:s", strtotime($ds->time));
            $date = date("d.m.Y", strtotime($ds->date));

            array_push($array, array(
                'chat_user' => $ds->user,
                'chat_username' => $ds->username,
                'chat_nachricht' => $ds->nachricht,
                'chat_date' => $ds->date,
                'chat_time' => $ds->time
            ));
        }

        echo json_encode($array);
    } else {

    }



}

And html:

    <ul class="messages">

    </ul>

i worked not really much with jquery! i dont know how i can do that. i hope anyone could help me

Upvotes: 0

Views: 790

Answers (2)

Rajesh Grandhi
Rajesh Grandhi

Reputation: 378

My Suggestion is :

1).Get the current html using the root div id.(i.e $('#testBlock').html());

2) Place one div inside the html you got from above command.Add current message inside the div added.

Upvotes: 2

Felix Fong
Felix Fong

Reputation: 985

You can use the append function to add new HTML tag

$('.showMsgArea').append(msg);

Upvotes: 0

Related Questions