TrinityTuts

Simple Chat application with Php, Ajax and MySql

Last updated on January 8th, 2020 at 10:21 pm

Chat application is very common in web today. In this post i will explain you how to create a simple chat application using PHP, Ajax and MySql. Before we start creating Chat application try a live demo of the app which are we going to create.

 

The chat application we are building is very simple. It include a start form where user enter his email address and also enter his friend email which he want to chat and same thing done by his friend we use these email as unique and send their message to each other.

 

Step 1 : HTML Markup

First we create a start page {index.php} where user enter his email and his friend email address as shown in above image.

<form method="post" action="chat.php">
		<div>
			<label for="email">Your Email</label>
			<input type="email" name="myid" value="" id="email" required="required">
		</div>
		<div>
			<label for="femail">Friend Email</label>
			<input type="email" name="fid" value="" id="femail" required="required">
		</div>
		<div>
			<input type="submit" value="Done!">
		</div>
</form>

Step 2 : Chat Room

After filling all information in index page { index.php } we display a chat box to user to start chat with his friend.  I create a simple box where user type his message to his friend and friend reply.

i create a simple form to do that thing and use ajax to send and receive message between both.

<?php
if(isset($_POST['myid']) && isset($_POST['fid'])){
	$myid = $_POST['myid'];
	$fid = $_POST['fid'];
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Chat</title>
<script src="jquery.min.js"></script>
<script src="moment.min.js"></script>
<script src="livestamp.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
	<div class="container">
      <div class="chat" id="chat">
        <div class="stream" id="cstream">

      </div>
      </div>
      <div class="msg">
          <form method="post" id="msenger" action="">
            <textarea name="msg" id="msg-min"></textarea>
            <input type="hidden" name="mid" value="<?php echo $myid;?>">
            <input type="hidden" name="fid" value="<?php echo $fid;?>">
            <input type="submit" value="Send" id="sb-mt">
          </form>
      </div>
      <div id="dataHelper" last-id=""></div>
  </div>
<script type="text/javascript">
$(document).keyup(function(e){
	if(e.keyCode == 13){
		if($('#msenger textarea').val().trim() == ""){
			$('#msenger textarea').val('');
		}else{
			$('#msenger textarea').attr('readonly', 'readonly');
			$('#sb-mt').attr('disabled', 'disabled');	// Disable submit button
			sendMsg();
		}		
	}
});	

$(document).ready(function() {
    $('#msg-min').focus();
	$('#msenger').submit(function(e){
		$('#msenger textarea').attr('readonly', 'readonly');
		$('#sb-mt').attr('disabled', 'disabled');	// Disable submit button
		sendMsg();
		e.preventDefault();	
	});
});

function sendMsg(){
	$.ajax({
		type: 'post',
		url: 'chatM.php?rq=new',
		data: $('#msenger').serialize(),
		dataType: 'json',
		success: function(rsp){
				$('#msenger textarea').removeAttr('readonly');
				$('#sb-mt').removeAttr('disabled');	// Enable submit button
				if(parseInt(rsp.status) == 0){
					alert(rsp.msg);
				}else if(parseInt(rsp.status) == 1){
					$('#msenger textarea').val('');
					$('#msenger textarea').focus();
					//$design = '<div>'+rsp.msg+'<span class="time-'+rsp.lid+'"></span></div>';
					$design = '<div class="float-fix">'+
									'<div class="m-rply">'+
										'<div class="msg-bg">'+
											'<div class="msgA">'+
												rsp.msg+
												'<div class="">'+
													'<div class="msg-time time-'+rsp.lid+'"></div>'+
													'<div class="myrply-i"></div>'+
												'</div>'+
											'</div>'+
										'</div>'+
									'</div>'+
								'</div>';
					$('#cstream').append($design);

					$('.time-'+rsp.lid).livestamp();
					$('#dataHelper').attr('last-id', rsp.lid);
					$('#chat').scrollTop($('#cstream').height());
				}
			}
		});
}
function checkStatus(){
	$fid = '<?php echo $fid; ?>';
	$mid = '<?php echo $myid; ?>';
	$.ajax({
		type: 'post',
		url: 'chatM.php?rq=msg',
		data: {fid: $fid, mid: $mid, lid: $('#dataHelper').attr('last-id')},
		dataType: 'json',
		cache: false,
		success: function(rsp){
				if(parseInt(rsp.status) == 0){
					return false;
				}else if(parseInt(rsp.status) == 1){
					getMsg();
				}
			}
		});	
}

// Check for latest message
setInterval(function(){checkStatus();}, 200);

function getMsg(){
	$fid = '<?php echo $fid; ?>';
	$mid = '<?php echo $myid; ?>';
	$.ajax({
		type: 'post',
		url: 'chatM.php?rq=NewMsg',
		data:  {fid: $fid, mid: $mid},
		dataType: 'json',
		success: function(rsp){
				if(parseInt(rsp.status) == 0){
					//alert(rsp.msg);
				}else if(parseInt(rsp.status) == 1){
					$design = '<div class="float-fix">'+
									'<div class="f-rply">'+
										'<div class="msg-bg">'+
											'<div class="msgA">'+
												rsp.msg+
												'<div class="">'+
													'<div class="msg-time time-'+rsp.lid+'"></div>'+
													'<div class="myrply-f"></div>'+
												'</div>'+
											'</div>'+
										'</div>'+
									'</div>'+
								'</div>';
					$('#cstream').append($design);
					$('#chat').scrollTop ($('#cstream').height());
					$('.time-'+rsp.lid).livestamp();
					$('#dataHelper').attr('last-id', rsp.lid);	
				}
			}
	});
}
</script>
</body>
</html>

Now i split this code to help you understand this .

<?php
if(isset($_POST['myid']) && isset($_POST['fid'])){
	$myid = $_POST['myid'];
	$fid = $_POST['fid'];
}
?>

First i get both email address and save that address to a variable. Now i create a simple html form to allow user to type his message and display that send message in chat box.

<div class="container">
      <div class="chat" id="chat">
        <div class="stream" id="cstream">

      </div>
      </div>
      <div class="msg">
          <form method="post" id="msenger" action="">
            <textarea name="msg" id="msg-min"></textarea>
            <input type="hidden" name="mid" value="<?php echo $myid;?>">
            <input type="hidden" name="fid" value="<?php echo $fid;?>">
            <input type="submit" value="Send" id="sb-mt">
          </form>
      </div>
      <div id="dataHelper" last-id=""></div>
  </div>

Note in above form i create two hidden fields where i echo both my email address{mid} and my friend email{fid}

  <input type="hidden" name="mid" value="<?php echo $myid;?>">
            <input type="hidden" name="fid" value="<?php echo $fid;?>">

to make conversation between both after that i create a simple javascript function to send and receive message from database. I use Jquery plugin to make thing work and also use livestamp plugin to display the time of message eg.{a second ago, a minute ago, 1 min, …..}

<script src="jquery.min.js"></script>
<script src="moment.min.js"></script>
<script src="livestamp.js"></script>


// Function to make thing possible
sendMsg(); // to send message

checkStatus(); // to check if friend make new message

getMsg(); // load new message from database

 

function sendMsg(){ $.ajax({ type: 'post', url: 'chatM.php?rq=new', data: $('#msenger').serialize(), dataType: 'json', success: function(rsp){ $('#msenger textarea').removeAttr('readonly'); $('#sb-mt').removeAttr('disabled'); // Enable submit button if(parseInt(rsp.status) == 0){ alert(rsp.msg); }else if(parseInt(rsp.status) == 1){ $('#msenger textarea').val(''); $('#msenger textarea').focus(); //$design = '<div>'+rsp.msg+'<span class="time-'+rsp.lid+'"></span></div>'; $design = '<div class="float-fix">'+ '<div class="m-rply">'+ '<div class="msg-bg">'+ '<div class="msgA">'+ rsp.msg+ '<div class="">'+ '<div class="msg-time time-'+rsp.lid+'"></div>'+ '<div class="myrply-i"></div>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'; $('#cstream').append($design); $('.time-'+rsp.lid).livestamp(); $('#dataHelper').attr('last-id', rsp.lid); $('#chat').scrollTop($('#cstream').height()); } } }); } function checkStatus(){ $fid = '<?php echo $fid; ?>'; $mid = '<?php echo $myid; ?>'; $.ajax({ type: 'post', url: 'chatM.php?rq=msg', data: {fid: $fid, mid: $mid, lid: $('#dataHelper').attr('last-id')}, dataType: 'json', cache: false, success: function(rsp){ if(parseInt(rsp.status) == 0){ return false; }else if(parseInt(rsp.status) == 1){ getMsg(); } } }); } // Check for latest message setInterval(function(){checkStatus();}, 200); function getMsg(){ $fid = '<?php echo $fid; ?>'; $mid = '<?php echo $myid; ?>'; $.ajax({ type: 'post', url: 'chatM.php?rq=NewMsg', data: {fid: $fid, mid: $mid}, dataType: 'json', success: function(rsp){ if(parseInt(rsp.status) == 0){ //alert(rsp.msg); }else if(parseInt(rsp.status) == 1){ $design = '<div class="float-fix">'+ '<div class="f-rply">'+ '<div class="msg-bg">'+ '<div class="msgA">'+ rsp.msg+ '<div class="">'+ '<div class="msg-time time-'+rsp.lid+'"></div>'+ '<div class="myrply-f"></div>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'; $('#cstream').append($design); $('#chat').scrollTop ($('#cstream').height()); $('.time-'+rsp.lid).livestamp(); $('#dataHelper').attr('last-id', rsp.lid); } } });

these function are the backbone of the whole chat system. I also handle enter button so whenever user type new message to friend and hit enter button message is send to database and also if user like to press submit button.

// When user hit enter on keyboard send message
$(document).keyup(function(e){
	if(e.keyCode == 13){
		if($('#msenger textarea').val().trim() == ""){
			$('#msenger textarea').val('');
		}else{
			$('#msenger textarea').attr('readonly', 'readonly');
			$('#sb-mt').attr('disabled', 'disabled');	// Disable submit button
			sendMsg();
		}		
	}
});	

// Send message to database when user press submit button
$(document).ready(function() {
    $('#msg-min').focus();
	$('#msenger').submit(function(e){
		$('#msenger textarea').attr('readonly', 'readonly');
		$('#sb-mt').attr('disabled', 'disabled');	// Disable submit button
		sendMsg();
		e.preventDefault();	
	});
});

Step 3 : Backend for Chat

Now this is the most important part of chatroom where we can save data and send new message to user screen.

Database for Chat: 

--
-- Table structure for table `msg`
--

CREATE TABLE IF NOT EXISTS `msg` (
  `id` int(100) NOT NULL AUTO_INCREMENT,
  `to` text NOT NULL,
  `from` text NOT NULL,
  `msg` text NOT NULL,
  `status` text NOT NULL,
  `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=60 ;

I create a simple database for my chat where i save both email address, status of message and time of message.

Here status by default is set to 1 mean new message and when user read that message it change to .

Code to handle all chat room request: chatM.php

<?php
// Connection
$conn = mysql_connect("localhost", 'root', '');
$db = mysql_select_db("mychat", $conn);
$json = '';
if(isset($_GET['rq'])):
	switch($_GET['rq']):
		case 'new':
			$msg = $_POST['msg'];
			$myid = $_POST['mid'];
			$fid = $_POST['fid'];
			if(empty($msg)){
				//$json = array('status' => 0, 'msg'=> 'Enter your message!.');
			}else{
				$qur = mysql_query('insert into msg set `to`="'.$fid.'", `from`="'.$myid.'", `msg`="'.$msg.'", `status`="1"');
				if($qur){
					$qurGet = mysql_query("select * from msg where id='".mysql_insert_id()."'");
					while($row = mysql_fetch_array($qurGet)){
						$json = array('status' => 1, 'msg' => $row['msg'], 'lid' => mysql_insert_id(), 'time' => $row['time']);
					}
				}else{
					$json = array('status' => 0, 'msg'=> 'Unable to process request.');
				}
			}
		break;
		case 'msg':
			$myid = $_POST['mid'];
			$fid = $_POST['fid'];
			$lid = $_POST['lid'];
			if(empty($myid)){

			}else{
				//print_r($_POST);
				$qur = mysql_query("select * from msg where `to`='$myid' && `from`='$fid' && `status`=1");
				if(mysql_num_rows($qur) > 0){
					$json = array('status' => 1);
				}else{
					$json = array('status' => 0);
				}
			}
		break;
		case 'NewMsg':
			$myid = $_POST['mid'];
			$fid = $_POST['fid'];

			$qur = mysql_query("select * from msg where `to`='$myid' && `from`='$fid' && `status`=1 order by id desc limit 1");
			while($rw = mysql_fetch_array($qur)){
				$json = array('status' => 1, 'msg' => '<div>'.$rw['msg'].'</div>', 'lid' => $rw['id'], 'time'=> $rw['time']);
			}
			// update status
			$up = mysql_query("UPDATE `msg` SET  `status` = '0' WHERE `to`='$myid' && `from`='$fid'");
		break;
	endswitch;
endif;

@mysql_close($conn);
header('Content-type: application/json');
echo json_encode($json);
?>

In above code i create my database connection and perform Insert and delete operation with php and return all result in json format. This is a simple chat room you can try live demo or download complete file from above link Thank you.