PHP

How to build Ajax based chat application in PHP

17th Jan, 2021
BY: RAHUL RANJAN   COMMENT (0)
How to build Ajax based chat application in PHP
Share Deals

Chat application helps you communicate with other online users at the same time. It can be either used in any business to solve a customer problem or can simply be used to share thoughts among users.

In this tutorial, we are going to build an ajax based chat application using PHP. Our chat application will be like a group chat where multiple people can join and chat together. Let us get started.

Database table for our chat application

Our database will consist of 3 tables users, chatroom, and chat_data. So, copy and run the following MySQL query to create the table:

chat.sql

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `password` varchar(20) NOT NULL,
  `current_session` int(11) NOT NULL,
  `online` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users` (`username`,`password`) VALUES ('demo1','demo1');
INSERT INTO `users` (`username`,`password`) VALUES ('demo2','demo2');
INSERT INTO `users` (`username`,`password`) VALUES ('demo3','demo3');

CREATE TABLE IF NOT EXISTS `chatroom` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `room_name` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `chatroom` (`room_name`) VALUES ('avengers');

CREATE TABLE IF NOT EXISTS `chat_data` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userid` varchar(20) NOT NULL,
  `chatroom_id` varchar(20) NOT NULL,
  `message` text NOT NULL,
  `chattime` varchar(25) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Connecting to the database

As we are done with our database part, now we will write a PHP script to connect to the database.
Create a file named "db.php" and copy & paste the below code in it:

db.php

<?php 
session_start();
$mysql_hostname  =  "localhost";
$mysql_user  =  "username";
$mysql_password  =  "password";
$mysql_database  =  "chatdemo";
$con  =  mysqli_connect($mysql_hostname,$mysql_user,$mysql_password,$mysql_database);
if(!$con){
	echo "Unable to connect to database";
	exit();
}
?>

Creating a form for our chat application

We will now create our chat form to make user login and add messaging functionality. Create a file named "index.php" and copy-paste the below code in it.

index.php

<?php
 include "db.php";
?>
<div id="header">
 <div class="user_login" <?php echo isset($_SESSION["userid"])?'style="display:none"':'';?>>
  <div class="user_input">
   <input class="input_user" placeholder="username" type="text" name="username" />
   <input class="input_pass" placeholder="password" type="text" name="password" />
  </div>
  <div class="action"><button class="doLogin">Login</button></div>
 </div>
 <div class="user_detail" <?php echo isset($_SESSION["userid"])?'style="display:block"':'';?>>
  <div class="username" data-id="<?php echo $_SESSION["userid"];?> "><?php echo $_SESSION["chat_user"];?></div>
  <div class="doLogout">Logout</div>
 </div>
</div>
<div id="room_block">
 <div class="head">Chat rooms</div>
  <ul class="room_list">
   <li data-room-id="12">avengers</li>
  </ul>
  <div class="online_d">(<span class="user_online">0</span>) online</div>
</div>
<div id="chat_block">
 <div class="message_area" data-chatroom="1">
 </div>
 <div class="message-box_login" <?php echo isset($_SESSION["userid"])?'style="display:none"':'';?>>
   Please login using above credentials to start messaging
 </div>
 <div class="message-box" <?php echo isset($_SESSION["userid"])?'style="display:block"':'';?>>
  <div class="msg_input">
   <textarea class="message" placeholder="Enter message..."></textarea>
  </div>
  <div class="msg_submit">
   <button class="msg_send">SEND</button>
  </div>
 </div>
</div>

Ajax scripts for chat application

Now we will write javascript code to enable login, logout, messaging, and online user functionality. Copy and paste the below code in a file named "script.js":

script.js

var scrollDone = 0;
function onLogin(data){
 $(".input_user").val("");
 $(".input_pass").val("");
 $(".user_login").hide();
 $(".user_detail").show();
 $(".message-box_login").hide();
 $(".message-box").show();
 $(".user_detail>.username").html(data.chat_user).attr("data-id",data.user_id);
}
function onLogout(data){
 $(".input_user").val("");
 $(".input_pass").val("");
 $(".user_login").show();
 $(".user_detail").hide();
 $(".message-box_login").show();
 $(".message-box").hide();
 $(".user_detail>.username").html("").attr("data-id","");
}
$(".doLogin").on('click',function(){
 let username = $(".input_user").val();
 let password = $(".input_pass").val();
 $.ajax({
  url:"checklogin.php",
  method:"POST",
  data:{action:'login',username:username,password:password},
  success:function(response){
   console.log(response);
   var obj = JSON.parse(response);
   console.log(obj);
   if(obj.status=="error"){
    alert(obj.message);
   }else{
    onLogin(obj);
    $(".message_area").html("");
   }
  }
 });
});
$(".doLogout").on('click',function(){
 $.ajax({
  url:"logout.php",
  method:"POST",
  data:{action:'logout'},
  success:function(response){
   onLogout();
  }
 });
});
function input_filter(data){
 if(data=='undefined' || data==null){
  return "";
 }
 return data;
}
function get_chat_data(){
 id=$(".user_detail>.username").attr("data-id");
 msg_id = input_filter($(".message_area div:last").attr("data-msg-id"));
 chatroom_id = $(".message_area").attr("data-chatroom");
 $.ajax({
  url:"chat.php",
  method:"POST",
  data:{action:'getdata',data_id:id,last_id:msg_id,chatroom_id:chatroom_id},
  success:function(response){
   data = JSON.parse(response);
   $(".user_online").html(data.online);
   message = data.new_message;
   $(".message_area").append(message);
   if(scrollDone==0 || message!=""){
    scrollOnce();
    scrollDone=1;
   }
  }
 });
}
function scrollOnce(){
 $(".message_area").animate({ scrollTop: $('.message_area').prop("scrollHeight")}, 1000);
} $(".msg_send").on('click',function(){
 let msg_text = $(".message").val();
 id=$(".user_detail>.username").attr("data-id");
 chatroom_id = $(".message_area").attr("data-chatroom");
 $.ajax({
  url:"insertchat.php",
  method:"POST",
  data:{action:'insert',message:msg_text,id:id,chatroom_id:chatroom_id},
  success:function(response){
   //if sent successfully will by updated by get_chat_data
   $(".message").val("");
   scrollDone = 0;
  }
 });
});
setInterval(get_chat_data, 1500); //Get update in 1.5s

Note: Above script requires the jquery library to work, so please include the latest jquery library before this script.

Checking User login

To verify user login, create a file named "checklogin.php" and place the code given below into it.

checklogin.php

<?php
include "db.php";
$error=0;
if(isset($_POST["action"])){
 $username = mysqli_real_escape_string($con,$_POST["username"]);
 $password = mysqli_real_escape_string($con,$_POST["password"]);
 if($username!="" && $password!=""){
  $query = mysqli_query($con,"select * from users where `username` = '$username' and `password` = '$password'");
  $c_rows  =  mysqli_num_rows($query);
  $rows=mysqli_fetch_array($query);
  $getId=$rows["id"];
  if  ($c_rows<=0)  {
   $error=1;
  }
  if($error==0)
  {
   $_SESSION["chat_user"]=$username;
   $_SESSION["userid"]=$getId;
   $output = array(
    "status" => 'success',
    "user_id" => $getId,
    "chat_user" => $username,
   );
   $time = time();
   mysqli_query($con,"update users set `online` = '1',current_session = '$time' where `id` = '$getId'");
   echo json_encode($output);
  }else{
   $output = array(
    "status" => 'error',
    "message" => 'Invalid Credentials',
   );
   echo json_encode($output);
  }
  
 }else{
  $output = array(
   "status" => 'error',
   "message" => 'Please fill all fields.',
  );
  echo json_encode($output);
 }
}else{
 $output = array(
  "status" => 'error',
  "message" => 'Oops! some error occurred.',
 );
 echo json_encode($output);
}
?>

Inserting sent message in the database

Create a file named "insertchat.php" and copy & paste the below code into it.

insertchat.php

<?php
error_reporting(0);
include "db.php";
session_start();
if(isset($_POST["action"])){
 $userid=$_SESSION["userid"];
 $chatroom_id=$_POST["chatroom_id"];
 $message=mysqli_real_escape_string($con,$_POST['message']);
 $time=time();
 $sql=mysqli_query($con,"insert into chat_data (`userid`,`chatroom_id`,`message`,`chattime`) values ('$userid','$chatroom_id','$message','$time')");
}else{
 exit();
}
?>

Ajax functionality to update data

Now we will create a file that will update data on every user's screen at the interval of 1.5 seconds. This file will provide details of online users and the latest chat messages. Create a file name "chat.php" and add the below code into it.

chat.php

<?php
include "db.php";
$error=0;
$timestamp_diff = 10; //logout if inactive for 20 seconds
$chat_data = array(
 'online' => 0,
 'new_message' => "",
);
if(isset($_POST["action"])){
 $user_id = $_POST["data_id"]==""?0:mysqli_real_escape_string($con,$_POST["data_id"]);
 $chatroom_id = mysqli_real_escape_string($con,$_POST["chatroom_id"]);
 $query = mysqli_query($con,"select * from users");
 //Loop through all users
 if(mysqli_num_rows($query)>0){
  $online_count = 0;
  //Collect online users
  while($store = mysqli_fetch_array($query)){
 //Update user's timestamp
   $time=time();
   if((int)$store["id"] == (int)$user_id){
    //update timestamp
    mysqli_query($con,"update users set `online` = '1',`current_session` = '$time' where `id` = '$user_id'");
    $store["current_session"] =$time;
   }
   if(($time - $store["current_session"])>$timestamp_diff){
    //set user as offline
    $curr_id = $store["id"];
    mysqli_query($con,"update users set `online` = '0' where `id` = '$curr_id'");
   }else{
    $online_count++;
   }
  }
  $chat_data["online"] = $online_count;
//get latest messages after last_id
  if(isset($_POST["last_id"])){
   $last_id = ($_POST["last_id"]!="") ? mysqli_real_escape_string($con,$_POST["last_id"]):0; //set to 0 if no chat message loaded
   $query = mysqli_query($con,"select * from chat_data where `chatroom_id` = '$chatroom_id' and `id` > '$last_id'");
   $new_chat_data = "";
   while($store = mysqli_fetch_array($query)){
    if((int)$store["userid"]==(int)$user_id){
     $new_chat_data.='<div class="sent" data-msg-id="'.$store["id"].'">'.$store['message'].'</div>';
    }else{
     $new_chat_data.='<div class="received" data-msg-id="'.$store["id"].'">'.$store['message'].'</div>';
    }
   }
   $chat_data["new_message"] = $new_chat_data;
  }
 }
 echo json_encode($chat_data);
}?>

Logout user

Create a file named "logout.php" and add the below code into it:

logout.php

<?php
session_start();
$v=$_SESSION['user'];
$v1=$_SESSION['userid'];
session_destroy();
?>

Demo   Download

You can read about Creating a simple registration form using PHP and Mysql.
Thanks for reading this tutorial. I hope this tutorial helped you understand how to build an ajax based chat application in PHP. Please provide your query and valuable feedback in the comment box given below.

Do you have any questions related to this article? Ask away in the comments section below!
Hi Guest!, Login into our network to make comment more simple. Log in
userProfile
0 COMMENTS