1

i am trying to build a simple chat system but I'm not sure what needs to be done in order for when i submit my message, that message will update on a different computer browser.

Right now when i submit a message it gets stored in a database through an ajax call, in the same moment i display that message to in the chat.

any ideas?

thanks

Patrioticcow
  • 26,422
  • 75
  • 217
  • 337
  • 1
    See this answer to a very similar question: http://stackoverflow.com/questions/9363572/php-reload-chat-box/9363721#9363721 – Basti Feb 21 '12 at 17:59

2 Answers2

1

You have to check the server at certain time interval for updates. You can use setInterval() function for that.

Below is a simple example and it updates the chat messages every 3 seconds in the innerhtml of a div named chatdiv.

You have to store the chatid in a hidden field named chatid.

function updateRow()
{
    chatid = $("#chatid").val(); //hidden field which contains the current chat id. 
    $.ajax({
       type: "POST",
        url: "update.php", 
        data: {"chatid":chatid},
        success: function (output) {
             $('#chatdiv').html(output); //updates the output to a div
        }
    });
}
setInterval("updateRow()",3000); //call updateRow() function every 3 seconds.

In update.php you can fetch the chat messages from database and echo it. For example,

$id = $_POST['chatid'];
$msg = $dbcon->queryUniqueValue("select message from chat where id=$id");
echo $msg;
nithi
  • 3,725
  • 2
  • 20
  • 18
0

You need to poll server and update with some interval, take a look at setInterval() function. Just update with fresh chat data every listener, should be enought for your case.

Aurimas Ličkus
  • 9,886
  • 4
  • 24
  • 26