Tom Cruise Tom Cruise - 3 months ago 19
jQuery Question

create real-time-like chat using only ajax, php and mysql

I'm using this ajax to fetch messages now. But new messages are not coming without refreshing.

function message(person2roll) {
$.ajax({
type:'POST',
url: 'getmessages.php',
data:{person2roll:person2roll},
success: function(data){
$('#message-area').html(data);
},
error:function (){}
});
}


And In my
getmessages.php
, I've written this query

$stmt = $conn->prepare('SELECT * FROM `message` WHERE (person1=? or person2=?) and (person1=? or person2=?) order by mess_date');
$stmt->bind_param('ssss', $roll, $roll, $person2roll, $person2roll);
$stmt->execute();
$result = $stmt->get_result();


This works correctly but new messages are not showing up without refresh.
How can I write a new ajax code to get only new messages and append it to div ?

Update: I'm calling message(person2roll) on clicking on user. It sends their id to the php file through ajax. I can't use set interval because it will refresh div every n seconds and this will make problem while scrolling. I only want to get new messages and append it to a div.

Answer

This works totally fine.

$(document).ready(function () {
    setInterval(function(){
        message(person2roll);
    },100);
});

function message(person2roll) {
    $.ajax({
        type: 'POST',
        url: 'getmessages.php',
        data: {person2roll: person2roll},
        success: function(data){
            $('#message-area').append(data);
        },
        error:function (){}
    });
}