I received lot of email requests from my reader that asked to me how to develop a facebook lite chat application. In this post I'm just giving an idea about chat application with simple javascript. I had implemented this at clouds.9lessons.info

CREATE TABLE chat

(

id INT PRIMARY KEY AUTO_INCREMENT ,

user VARCHAR(50) UNIQU E ,

msg VARCHAR(200),

);







Contains PHP, Javascript and HTML code. Run this file with

<?php

include ( 'db.php' );

if( $_GET [ 'user' ])

{

$user= $_GET [ 'user' ];

?>

<script type=" text/javascript " src=" http://ajax.googleapis.com/

ajax/libs/jquery/1.4.2/jquery.min.js " > </script>

<script type=" text/javascript " >

var user=' <?php echo $user; ?> ';

// Requesting to Database every 2 seconds

var auto_refresh = setInterval (function ()

{

var last_id=$( "ol#update li:last" ).attr( "id" );

$ . getJSON ( "chat_json.php?q=" +user,function(data)

{

$.each(data.posts, function(i,data)

{

if(last_id != data.id)

{

var div_data= "<li id='"+ data.id +"'><b>"+ data.user +"</b>: "+ data.msg +"</li>" ;

$(div_data). appendTo ( "ol#update" );

}

});

});

}, 2000 );



// Inserting records into chat table

$( document ). ready (function()

{

$( '.post' ). click (function()

{

var boxval = $( "#content" ).val();

var user = ' <?php echo $user; ?> ';

var dataString = 'user=' + user + '&msg=' + boxval;

if(boxval.length > 0)

{

$.ajax({

type: " POST ",

url: " chatajax.php ",

data: dataString,

cache: false ,

success: function(html)

{

$( "ol#update" ). append (html);

$( '#content' ).val('');

$( '#content' ).focus();

}

});

}

return false;

});

});

</script>

// HTML code

<div>

<form method=" post " name=" form " action="">

<input type=' text ' name=" content " id=" content " />

<input type=" submit " value=" Post " id=" post " class=" post "/>

</form>

</div>

<?php } ?>

Contains PHP code. Inserting records into chat table.

<?php

include ( 'db.php' );

if( $_POST )

{

$user= htmlentities ( $_POST [ 'user' ]);

$msg= htmlentities ( $_POST [ 'msg' ]);

$user= mysql_escape_String ($user);

$msg= mysql_escape_String ($msg);

mysql_query ( "insert into chat(user,msg)values('$user','$msg')" );

$sql= mysql_query ( "select id from chat where user='$user' order by id desc limit 1" );

$row= mysql_fetch_array ($sql);

$id=$row['id'];

?>

<li id=" <?php echo $id; ?> ">

<b> <?php echo $user; ?> :</b> <?php echo $msg; ?>

</li>

<?php

}

?>

Contains PHP code getting latest record from the chat table and output result in JSON format.

<?php

include ( 'db.php' );

if( $_GET [ 'q' ])

{

$user= $_GET [ 'q' ];

$sql = mysql_query ( "select * from chat order by id desc limit 1" );

$row= mysql_fetch_array ($sql);

$userx=$row[ 'user' ];

$id=$row[ 'id' ];

$msg=$row[ 'msg' ];

if($userx != $user)

{

echo ' {"posts": [ ';

echo '

{

"id":"'.$id.'",

"user":"'.$userx.'",

"msg":"'.$msg.'"

}, ';

echo ']} ' ;

} }

?>

PHP database configuration file