How To Create Chat System in PHP Using Ajax

0 74,630

Hello Guys in this article we are going to discuss Chat system. what is Chat System? A chat is a system that allows user to communicate in real time using easily accessible web interfaces. and in this tutorial, we teach your how to create chat system in PHP MySQL using Ajax. the help of this chat system that people use their name and message start chat with the active users who are online.

How To Create Chat System in PHP Using Ajax

Creating Database

in this step we are going to create database where store our data.

  • Open Phpmyadmin
  • Click on database Give the Database Name “Chat“.
  • After Creating Database open it.
  • Click on SQL Tab
  • Copy the below source code and paste it.
  • Click on GO.
-- phpMyAdmin SQL Dump
-- version 4.2.7.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jan 21, 2016 at 06:45 PM
-- Server version: 5.6.20
-- PHP Version: 5.5.15

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `chat`
--

-- --------------------------------------------------------

--
-- Table structure for table `chat`
--

CREATE TABLE IF NOT EXISTS `chat` (
`id` int(50) NOT NULL,
  `name` varchar(255) NOT NULL,
  `msg` varchar(255) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=32 ;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `chat`
--
ALTER TABLE `chat`
 ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `chat`
--
ALTER TABLE `chat`
MODIFY `id` int(50) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=32;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Creating Database Connection

Next step is creating Database connection. Firstly open HTML Editor Like Notepad++ and copy the below code and paste. Then save it as “db.php”.

<?php 
$host = "localhost"; 
$user = "root";
$pass = ""; 
$db_name = "chat"; 

$con = new mysqli($host,$user,$pass,$db_name);

function formatDate($date){
	return date('g:i a', strtotime($date));
}
?>

Creating Form

Next step is creating a Simple HTML form where send message. Copy the below source code and save it is as “index.php”.

<!DOCTYPE html> 
<html>
	<head>
		<title>Chat System in PHP</title>
		<!--Include Custom CSS-->
		<link rel="stylesheet" href="css/style.css" media="all"/>
		<!--Bootstrap CSS file-->
		<link rel="stylesheet" href="css/bootstrap.css">
		<!--Include Jquery File-->
		<script src="js/jquery.js"></script>
		<!--Include Bootstrap JS File-->
		<script src="js/bootstrap.js"></script>
	<script>
		function ajax(){
		
		var req = new XMLHttpRequest();
		
		req.onreadystatechange = function(){
		
		if(req.readyState == 4 && req.status == 200){
		
		document.getElementById('chat').innerHTML = req.responseText;
		} 
		}
		req.open('GET','includes/chat.php',true); 
		req.send();
		
		}
		setInterval(function(){ajax()},1000);
	</script>
	</head>
	
<body onload="ajax();">


	<div id="container">
		<div class="row">
			<div class="col-sm-2 col-md-6">	
				<h1 class="alert alert-success">Live Chat</h1>
				<h1 class="alert alert-success">
					<form method="post" action="index.php">
			<div class="form-group">
				<input class="form-control" placeholder="Enter your Name" name="name" type="text">	
			</div>	
			<div class="form-group">
				<textarea class="form-control" placeholder="Your Message" name="msg"></textarea>	
			</div>	
			<div class="form-group">
				<input class="btn btn-success btn-block" name="send"  type="submit" value="Send">	
			</div>	
		
			</form>
		</div></h1>
		
			<div class="col-sm-2 col-md-6">	
				<div id="chat"></div></div>
				</div>
				</div>
			<?php 
			include 'includes/db.php';
			?>
			<?php 
			if(isset($_POST['send'])){ 
			
			$name = $_POST['name'];
			$messsage = $_POST['msg'];
			
			$query = "INSERT INTO chat (name,msg) values ('$name','$message')";
			
			$run = $con->query($query);
			}
			?>	
	</div>
</body>
</html>

Styling The Form

in this step we are going to create some styles for the form and make it attractive copy the below source code and save it is as “style.css”.

*{
	padding:0; 
	margin:0; 
	border:0;
}

body {
	background:silver;
}

#container {
	width:70%;
	background:white; 
	padding:20px;

}
#chat_box {
	width:90%; 
	height:400px;
}
#chat_data {
	width:100%; 
	padding:5px; 
	margin-bottom:5px;
	border-bottom:1px solid silver;
	font-weight:bold;
}

Validating Chat System Using PHP

Next step is validate chat system using PHP MySQL to send messages and receive message from database copy the below source code and save it as “chat.php”.

<br>
<?php 
	include 'db.php';
	
	$query = "SELECT * FROM chat";
	$run = $con->query($query);
	while($row = $run->fetch_array()) :
		?>
	
			<div id="chat_data">
				<span  class="btn btn-success glyphicon glyphicon-user">&nbsp;<b><?php echo $row['name']; ?></b></span>:
				<span style="color:green;"><?php echo $row['msg']; ?></span>
				<span style="float:right;"><?php echo formatDate($row['date']); ?></span>
			</div>
			<?php endwhile;?>
			

Preview

How to create chat system in PHP using Ajax How to create chat system in PHP using Ajax

Download Source Code

Leave A Reply

Your email address will not be published.