Dabrorius - WEB tutorials
jQuery AJAX PHP chat upgrade [PHP tutorials]
This is part 2 of jQuery chat tutorial. In this one we will add some functions to our old chat script.
We are going to add 3 new functions.

New Features

> Nicknames - users will be asked to enter nickname when entering chat
> Old Message Deleting - messages older than 1 minute will be deleted
> Send message when ENTER is pressed

Some other changes are

> we use div insted of textbox to show messages
> index.php is now chat.php
> we use config.php to connect to database

chat.sql

 
CREATE TABLE IF NOT EXISTS `chat` (
  `Id` int(11) NOT NULL auto_increment,
  `Text` text NOT NULL,
  `Time` bigint(20) NOT NULL,
  PRIMARY KEY  (`Id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=49 ;
 


We need to add one column to our table.
It will be used to save when message was posted so that we know when to delete it.

config.php (new file)


 
<?
session_start();
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
 
$conn = mysql_connect($dbhost, $dbuser, $dbpass) 
or die ('Error connecting to mysql');
 
$dbname = 'chat';
 
mysql_select_db($dbname);
?>
 


We use this code to connect to mysql database, it is same as in part 1 of this tutorial but it is saved into different file. I'll just include it wherever I need to work with database.

Also since we work with sessions now, we start a session here too.

index.php (new file)

So we use entirely different index.php, rename index.php from first tutorial to chat.php.

 
<html>
	<body>
		<form action="chat.php" method="post">
			Nickname: <input name="nickname">
			<input type="submit" value="Chat!">
		</form>
	</body>
</html>
 


It's just a simple form used to get nickname.

chat.php


 
<?
//new stuff --------
include('config.php');
 
if(isset($_POST['nickname']))
{
	$nick = $_POST['nickname'];	
	$_SESSION['nickname'] = $nick;
 
}
 
if(!isset($_SESSION['nickname'])) 
die("You are not logged in!");
//------------- END
?>
 
<html>
<head>
<script type="text/javascript" src="jquery-1.2.6.pack.js"></script>
<script type="text/javascript">  
 
function update()
{
	//new stuff --------	
    $.post("server.php", {}, function(data){ $("#screen").html(data);});  
	//------------------- END
 
    setTimeout('update()', 1000);
}
 
//new stuff --------	
function send_msg() 
    { 				    
	    $.post("server.php", 
		{ message: $("#message").val()},
		function(data){	
		$("#screen").html(data); 
		$("#message").val("");
		}
		);
    }
//------------------- END
 
$(document).ready(
 
function() 
    {
	    update();
 
	//new stuff --------	
	    $("#button").click(    
		    function() 
		    { 				    
			    send_msg();
		    }
		 );
 
	      $('#message').keyup(function(e) {	   
	      if(e.keyCode == 13) {	   
	   		send_msg();
	      }
	   //------------------- END
	      });
 
 
    });
 
 
</script>
</head>
<body>
 
<div id="screen" style="border:1px solid black; width:300; height:500;"> </div>
 <br>  
<input id="message" size="40">
<button id="button"> Send </button>
 
</body>
</html>
 


All new parts are marked with comments.
I will explain each one of them below.

 
include('config.php');
 


First we include config.php, we use that file to connect to mysql and start session. (see above)

 
if(isset($_POST['nickname']))
{
	$nick = $_POST['nickname'];	
	$_SESSION['nickname'] = $nick;	
}
 


We check if "nickname" was posted, and then we store it to session.

 
if(!isset($_SESSION['nickname'])) 
die("You are not logged in!");
 


If session is not set (someone is trying to enter chat without nickname, die and give error message.

 
$.post("server.php", {}, function(data){ $("#screen").html(data);});  
 


Since we use div now to show chat instead of textarea we need to change function from ".val(data)" to ".html(Data)". (.html() function is used to change html code inside div)

 
function send_msg() 
    { 				    
	    $.post("server.php", 
		{ message: $("#message").val()},
		function(data){	
		$("#screen").html(data); 
		$("#message").val("");
		}
		);
    }
 


We make a new function for sending messages.
Code inside is same as in part 1 of this tutorial.

 
 $("#button").click(    
		    function() 
		    { 				    
			    send_msg();
		    }
		 );
 


If button with id = button is clicked, send message.

 
 $('#message').keyup(function(e) {	   
	      if(e.keyCode == 13) {	   
	   		send_msg();
	      }
	   //------
 


If ENTER is clicked while message field has focus, send message.

server.php


 
<?
//new stuff --------
include('config.php');
 
$nick = $_SESSION['nickname'];
 
$message = $_POST['message'];
$message = strip_tags($message);
$message = mysql_real_escape_string($message);
// -------------- END
 
if($message != "")
{
	//new stuff ---------
	$message = '<span style="color:blue;">'.$nick.': </span>'.$message;
	// -------------- END
 
	$sql = "INSERT INTO `chat` VALUES('','$message','".time()."')"; //new stuff
	mysql_query($sql);
}
 
//new stuff-------
$old = time() - 60;
$sql = "DELETE FROM `chat` WHERE `Time` < $old";
mysql_query($sql);
// -------------- END
 
$sql = "SELECT `Text` FROM `chat` ORDER BY `Id` DESC";
$result = mysql_query($sql);
 
while($row = mysql_fetch_array($result))
	echo $row['Text']."<br>"; //new stuff
 
 
?>
 


Let's take a look at new stuff.

 
include('config.php');
 


Connect to mysql and start session. (look config.php explanation above)

 
$nick = $_SESSION['nickname'];
 


Store session value nickname to variable $nick.
We do this just to make it shorter.

 
$message = $_POST['message'];
$message = strip_tags($message);
$message = mysql_real_escape_string($message);
 


This is SQL injection and XSS protection part.

 
$message = '<span style="color:blue;">'.$nick.': </span>'.$message;
 


We stick nickname to our message along with span tags to give it blue color.

 
$sql = "INSERT INTO `chat` VALUES('','$message','".time()."')";
 


When posting a new message put current time in last column.

 
$old = time() - 60;
$sql = "DELETE FROM `chat` WHERE `Time` < $old";
mysql_query($sql);
 


Delete all messages that are older then 60 seconds.
We subtract 60 from current time in seconds and then delete all messages that were posted before that.

 
echo $row['Text']."<br>"; 
 


Just replace "\n" with br tag.