yahoo5000 yahoo5000 - 10 months ago 59
jQuery Question

Live chat system using jQuery and PHP

I created chat box with jQuery and AJAX but the problem is that this chat box is not live. If you want to get newest record you have to refresh page. My code is quite simple and I would like to know what the best way to make it live.

This is my jQuery script :

$('#textbox').keypress(function(event) {
if(event.which == 13){


$('#post').submit(function() {
var userid = "<?php echo $_SESSION["userid"]; ?>";
var username = "<?php echo $_SESSION["username"]; ?>";
var message = $('#textbox').val();

$.post('post.php', { message: message, username: username, userid: userid }, function(data){
$('.chatwindow').append('<span class="msg" >' + username + ': </span>' + data + '</span><br>');
return false;

  1. Use AJAX to submit message and add to database.

    $.post("myscript.php", {userId: 123, message: "My message"});

  2. Every several seconds (i.e. 10 seconds) request newer messages by AJAX and prepend (or append) to discussion div.

    window.setInterval(function() { $.post("myscript.php", {action: "refresh", lastId: 1234}, function(response) { $("#discussion").prepend(response.html); lastId = response.lastId; }, "json"); }, 10000);