Wednesday, 4 July 2018

Live Chat System in PHP using Ajax JQuery



Chat App is a favorite application which every programmer want to be make their own chat application in their programming career. This Chat application mostly used to communicate with friends and in business world company has communicate with their customer to provide assistant or help to customer regarding their services or product which they has offered. So, it is very important application which required in every website or web application. So, this type of system we have start to make in step by step process by using PHP script with Ajax Jquery Mysql Bootstrap and JQuery UI library.

Do you know real time chat application, real time chat application means we can communicate multiple person at the same time, so there are many business houses use a chat application for communicate with their customer in real time and provide services. For the importance of this chat system we have decided to publish tutorial on chat application in php and mysql using Ajax JQuery.


So, in this post we are going to make simple chat application by using Ajax Jquery and PHP programming and Mysql database. Ajax with Jquery script is used to send and received request for data from client machine to server and server to client machine using PHP. It is mainly used for create real time application for send and received data without refresh of web page. In the real web world, we have generally use HTTP request GET and POST method for communication done between client and server side. In this PHP Chat application we have use Ajax Jquery to communicate with the server. Below you can find complete step by step process for create Chat Application in PHP using Ajax.




Database Structure for PHP Ajax Chat Application


Here this is Mysql database structure for PHP Mysql chat system. Following tables we will use to make chat app.


--
-- Database: `chat`
--

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

--
-- Table structure for table `chat_message`
--

CREATE TABLE `chat_message` (
  `chat_message_id` int(11) NOT NULL,
  `to_user_id` int(11) NOT NULL,
  `from_user_id` int(11) NOT NULL,
  `chat_message` text NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `status` int(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

--
-- Table structure for table `login`
--

CREATE TABLE `login` (
  `user_id` int(11) NOT NULL,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `login`
--

INSERT INTO `login` (`user_id`, `username`, `password`) VALUES
(1, 'johnsmith', '$2y$10$4REfvTZpxLgkAR/lKG9QiOkSdahOYIR3MeoGJAyiWmRkEFfjH3396'),
(2, 'peterParker', '$2y$10$4REfvTZpxLgkAR/lKG9QiOkSdahOYIR3MeoGJAyiWmRkEFfjH3396'),
(3, 'davidMoore', '$2y$10$4REfvTZpxLgkAR/lKG9QiOkSdahOYIR3MeoGJAyiWmRkEFfjH3396');

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

--
-- Table structure for table `login_details`
--

CREATE TABLE `login_details` (
  `login_details_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `last_activity` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `is_type` enum('no','yes') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `chat_message`
--
ALTER TABLE `chat_message`
  ADD PRIMARY KEY (`chat_message_id`);

--
-- Indexes for table `login`
--
ALTER TABLE `login`
  ADD PRIMARY KEY (`user_id`);

--
-- Indexes for table `login_details`
--
ALTER TABLE `login_details`
  ADD PRIMARY KEY (`login_details_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `chat_message`
--
ALTER TABLE `chat_message`
  MODIFY `chat_message_id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `login`
--
ALTER TABLE `login`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;

--
-- AUTO_INCREMENT for table `login_details`
--
ALTER TABLE `login_details`
  MODIFY `login_details_id` int(11) NOT NULL AUTO_INCREMENT;


Once you have make chat database and above table in your mysql database then you have to make database connection. For making database connection using PHP PDO we have to write following code.


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=chat", "root", "");

?>


Make Login and Logout page for chat application using PHP and Jquery




Once you have make database connection then after we want to make login and logout page for our PHP Mysql Chat system. We all know Login into a system is one type of process in which an user can gain access into our web application by identifying their authenticating their identity to system. So here for using our Live Chat Application we have to make Login and logout process, so we can authenticating user identity and get access them to gain our chat application. And by clicking on logout link they can leave our Chat app. Below you can find login source code for this PHP Ajax Chat script.








<!--
//login.php
!-->

<?php

include('database_connection.php');

session_start();

$message = '';

if(isset($_SESSION['user_id']))
{
 header('location:index.php');
}

if(isset($_POST["login"]))
{
 $query = "
   SELECT * FROM login 
    WHERE username = :username
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
    array(
      ':username' => $_POST["username"]
     )
  );
  $count = $statement->rowCount();
  if($count > 0)
 {
  $result = $statement->fetchAll();
    foreach($result as $row)
    {
      if(password_verify($_POST["password"], $row["password"]))
      {
        $_SESSION['user_id'] = $row['user_id'];
        $_SESSION['username'] = $row['username'];
        $sub_query = "
        INSERT INTO login_details 
        (user_id) 
        VALUES ('".$row['user_id']."')
        ";
        $statement = $connect->prepare($sub_query);
        $statement->execute();
        $_SESSION['login_details_id'] = $connect->lastInsertId();
        header("location:index.php");
      }
      else
      {
       $message = "<label>Wrong Password</label>";
      }
    }
 }
 else
 {
  $message = "<label>Wrong Username</labe>";
 }
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   <div class="panel panel-default">
      <div class="panel-heading">Chat Application Login</div>
    <div class="panel-body">
     <form method="post">
      <p class="text-danger"><?php echo $message; ?></p>
      <div class="form-group">
       <label>Enter Username</label>
       <input type="text" name="username" class="form-control" required />
      </div>
      <div class="form-group">
       <label>Enter Password</label>
       <input type="password" name="password" class="form-control" required />
      </div>
      <div class="form-group">
       <input type="submit" name="login" class="btn btn-info" value="Login" />
      </div>
     </form>
    </div>
   </div>
  </div>
    </body>  
</html>


This is simple login page code for our PHP Chat application. Here we have authenticate user details like username and password. If this both details is proper then he can get access into this online chat system. Otherwise it will get wrong information error on web page. Suppose user has enter proper details then he can get access into our live chat app. Here we have store hash password in database, so for validate hash password we have use password_verify() function. By using this function this system can authenticate user password. After authenticate process particular user details like user id and user name has been store into $_SESSION variable and this variable value we can from accross system. Particular user login details like his user id and timestamp details has been inserted into login_details table. After inserting their login details into database then last inserted id of login_details table has been get by using lastInsertId() method and store into $_SESSION['login_details_id'] variable. This data will help use to know particular user online status like he is onlin and offline. So, this whole discussion of login table.

After login in Chat Application user will be redirect to index page. Below you can find index page source code. This page cannot access directly without login into system because for access this page we want to login into system. So, authenticated used can only access this page. For this here we have validate $_SESSION['user_id'] variable value. Here you can find logout page link also.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header('location:login.php');
}
?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   
   <div class="table-responsive">
    <h4 align="center">Online User</h4>
    <p align="right">Hi - <?php echo $_SESSION['username']; ?> - <a href="logout.php">Logout</a></p>
    
   </div>
  </div>
    </body>  
</html>  


Above code is index.php code and this page can be access only after login into Chat system. Here we can see logout link also. Once we have click on this link we will be logout from this system and page has been redirect to login.php page. Below you can find logout.php page code.


<?php

//logout.php

session_start();

session_destroy();

header('location:login.php');

?>


Display User Data in PHP Ajax Chat system




After complete discuss of login and logout source code. Now we have move to next stage of Chat Application development and this stag is display all user data on web page when user login into Chat application and after validate user data then he will redirect to index.php page. On this page we want to display all user data which are available in login table. So login user can decide to which person he want to login. In this step we have simple fetch user data from login table and display on index page. Below you can source code for display user details on web page.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header("location:login.php");
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   
   <div class="table-responsive">
    <h4 align="center">Online User</h4>
    <p align="right">Hi - <?php echo $_SESSION['username'];  ?> - <a href="logout.php">Logout</a></p>
    <div id="user_details"></div>
   </div>
  </div>
    </body>  
</html>  




<script>  
$(document).ready(function(){

 fetch_user();

 function fetch_user()
 {
  $.ajax({
   url:"fetch_user.php",
   method:"POST",
   success:function(data){
    $('#user_details').html(data);
   }
  })
 }
 
});  
</script>



<?php

//fetch_user.php

include('database_connection.php');

session_start();

$query = "
SELECT * FROM login 
WHERE user_id != '".$_SESSION['user_id']."' 
";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

$output = '
<table class="table table-bordered table-striped">
 <tr>
  <td>Username</td>
  <td>Status</td>
  <td>Action</td>
 </tr>
';

foreach($result as $row)
{
 $output .= '
 <tr>
  <td>'.$row['username'].'</td>
  <td></td>
  <td><button type="button" class="btn btn-info btn-xs start_chat" data-touserid="'.$row['user_id'].'" data-tousername="'.$row['username'].'">Start Chat</button></td>
 </tr>
 ';
}

$output .= '</table>';

echo $output;

?>


Here we have create one
tag with id="user_details" tag, under this tag it will display user detail table format. For fetch details, here we have make function which send ajax request to fetch_user.php page. This fetch user data and converted into html and send to ajax function which has been display on webpage.

Display Online / Offline User Status in Live chat application




This is next step of How to create chat application in PHP and in this step we have discuss how to display online and offline status of user in real time chat system using PHP Ajax. Because if login can see particular is online then he can chat with online user and he cam make chat conversation with him. For this we want to display particular user status is online or offline. Online user means, user has login into system and he has stay on index.php page. For this we have write following source code for check user is status is online or offline in chat application using PHP.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header("location:login.php");
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   
   <div class="table-responsive">
    <h4 align="center">Online User</h4>
    <p align="right">Hi - <?php echo $_SESSION['username'];  ?> - <a href="logout.php">Logout</a></p>
    <div id="user_details"></div>
   </div>
  </div>
    </body>  
</html>  




<script>  
$(document).ready(function(){

 fetch_user();

 setInterval(function(){
  update_last_activity();
  fetch_user();
 }, 5000);

 function fetch_user()
 {
  $.ajax({
   url:"fetch_user.php",
   method:"POST",
   success:function(data){
    $('#user_details').html(data);
   }
  })
 }

 function update_last_activity()
 {
  $.ajax({
   url:"update_last_activity.php",
   success:function()
   {

   }
  })
 }
 
});  
</script>



<?php

//update_last_activity.php

include('database_connection.php');

session_start();

$query = "
UPDATE login_details 
SET last_activity = now() 
WHERE login_details_id = '".$_SESSION["login_details_id"]."'
";

$statement = $connect->prepare($query);

$statement->execute();

?>


First on index.php page we have make one function update_last_activity(), this function will ajax request to update_last_activity.php page for update login user last activity datatime details in login_details table. And this function we have called every 5 seconds by using setInterval() jquery method. Under this method we have also add fetch_user() function also. So on every 5 seconds this both function will be called, function will update login user datetime details under login_details table and second function fetch and display updated user details on webpage.


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=chat", "root", "");

date_default_timezone_set('Asia/Kolkata');

function fetch_user_last_activity($user_id, $connect)
{
 $query = "
 SELECT * FROM login_details 
 WHERE user_id = '$user_id' 
 ORDER BY last_activity DESC 
 LIMIT 1
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  return $row['last_activity'];
 }
}

?>


After this on database_connection.php page we have make one function fetch_user_last_activity(). This function will fetch particular user last_activity datetime data from login_details table. So, by using this function we can get particular user last activity datetime, so we can check user is online or not in Live Chat App using Ajax with PHP. For this things we have some code at fetch_user.php file. Below you can find that source code.


<?php

//fetch_user.php

include('database_connection.php');

session_start();

$query = "
SELECT * FROM login 
WHERE user_id != '".$_SESSION['user_id']."' 
";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

$output = '
<table class="table table-bordered table-striped">
 <tr>
  <td>Username</td>
  <td>Status</td>
  <td>Action</td>
 </tr>
';

foreach($result as $row)
{
 $status = '';
 $current_timestamp = strtotime(date("Y-m-d H:i:s") . '- 10 second');
 $current_timestamp = date('Y-m-d H:i:s', $current_timestamp);
 $user_last_activity = fetch_user_last_activity($row['user_id'], $connect);
 if($user_last_activity > $current_timestamp)
 {
  $status = '<span class="label label-success">Online</span>';
 }
 else
 {
  $status = '<span class="label label-danger">Offline</span>';
 }
 $output .= '
 <tr>
  <td>'.$row['username'].'</td>
  <td>'.$status.'</td>
  <td><button type="button" class="btn btn-info btn-xs start_chat" data-touserid="'.$row['user_id'].'" data-tousername="'.$row['username'].'">Start Chat</button></td>
 </tr>
 ';
}

$output .= '</table>';

echo $output;

?>


Above code we can see, we have add some code for check particular user is online or offline. For this here first we have store current date time in one variable and and from this datetime we have minus 10 seconds. After this we have store single user last activity datetime has been get by fetch_user_last_activity() and store in one variable. Now we can compare user last activity datetime data with current datetime. If user last activity datetime value greater than current datetime value that means user is login into system and his status will be online and if user last activity datetime value less than current datetime then user status will be offline. So this way we can display user status online or offline in web server based Chat application in PHP.

Make Dynamic Chat Box for Each User in Ajax PHP Chat Application




Now we come to main discussion of PHP Ajax Chat Application and here we have one question how can we generated dynamic chat dialog box for each user. Because this is main part in this via this dialog box user can chat with each other. For this how can we make dynamic chat dialog box for each. For this we have make one jquery function on index.php. This function will dynamically generate html code for chat dialog box. Here for chat dialog box we have use JQuery UI Dialog box plugin. So, when we have called this function this function will generate html code for chat dialog box. Below you can find source code for generating of dynamic chat dialog box.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header("location:login.php");
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   
   <div class="table-responsive">
    <h4 align="center">Online User</h4>
    <p align="right">Hi - <?php echo $_SESSION['username'];  ?> - <a href="logout.php">Logout</a></p>
    <div id="user_details"></div>
    <div id="user_model_details"></div>
   </div>
  </div>
    </body>  
</html>  




<script>  
$(document).ready(function(){

 fetch_user();

 setInterval(function(){
  update_last_activity();
  fetch_user();
 }, 5000);

 function fetch_user()
 {
  $.ajax({
   url:"fetch_user.php",
   method:"POST",
   success:function(data){
    $('#user_details').html(data);
   }
  })
 }

 function update_last_activity()
 {
  $.ajax({
   url:"update_last_activity.php",
   success:function()
   {

   }
  })
 }

 function make_chat_dialog_box(to_user_id, to_user_name)
 {
  var modal_content = '<div id="user_dialog_'+to_user_id+'" class="user_dialog" title="You have chat with '+to_user_name+'">';
  modal_content += '<div style="height:400px; border:1px solid #ccc; overflow-y: scroll; margin-bottom:24px; padding:16px;" class="chat_history" data-touserid="'+to_user_id+'" id="chat_history_'+to_user_id+'">';
  modal_content += '</div>';
  modal_content += '<div class="form-group">';
  modal_content += '<textarea name="chat_message_'+to_user_id+'" id="chat_message_'+to_user_id+'" class="form-control"></textarea>';
  modal_content += '</div><div class="form-group" align="right">';
  modal_content+= '<button type="button" name="send_chat" id="'+to_user_id+'" class="btn btn-info send_chat">Send</button></div></div>';
  $('#user_model_details').html(modal_content);
 }

 $(document).on('click', '.start_chat', function(){
  var to_user_id = $(this).data('touserid');
  var to_user_name = $(this).data('tousername');
  make_chat_dialog_box(to_user_id, to_user_name);
  $("#user_dialog_"+to_user_id).dialog({
   autoOpen:false,
   width:400
  });
  $('#user_dialog_'+to_user_id).dialog('open');
 });
 
});  
</script>


In Above source code which we have write index.php page. Here we can see make_chat_dialog_box() function. This function will generate chat dialog box for each user based on value of to_user_id and to_user_name argument. So, based on value of this both argument, this function will make dynamic chat dialog box for every user. Now when this function will be called, this function will be called when we have click on stat chat button. So here we can see jquery code in which we can see start chat button class .start_chat which is selector with click event. So when we have click on this button it will fetch value from data-touserid and data-tousername attribute and store in variable. After this it has called make_chat_dialog_box(to_user_id, to_user_name) function and it will make dynamic chat dialog box for particular user of which we have click on start chat button. So, this way we can make dynamic chat dialog box in our online chat application using PHP.

Insert Chat Message into Mysql Database




Once we have completed learning How can we create dynamic chat dialog box for our chat application in PHP. Now we want to know how can we insert chat message into database and display list of chat message in chat dialog box. So, when we have click on start chat button of any particular user then chat dialog box has been pop up on web page and in that box there is one textarea field in which we chat type chat message and click on send button then chat message will be inserted into database. After insert into database it will display all chat message conversation between two user will be display in chat dialog box without refresh of web page. Because it is a real time chat application which we have made by using PHP with Ajax. Below we can find source code of insert chat message into msyql database.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header("location:login.php");
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   
   <div class="table-responsive">
    <h4 align="center">Online User</h4>
    <p align="right">Hi - <?php echo $_SESSION['username'];  ?> - <a href="logout.php">Logout</a></p>
    <div id="user_details"></div>
    <div id="user_model_details"></div>
   </div>
  </div>
    </body>  
</html>  




<script>  
$(document).ready(function(){

 fetch_user();

 setInterval(function(){
  update_last_activity();
  fetch_user();
 }, 5000);

 function fetch_user()
 {
  $.ajax({
   url:"fetch_user.php",
   method:"POST",
   success:function(data){
    $('#user_details').html(data);
   }
  })
 }

 function update_last_activity()
 {
  $.ajax({
   url:"update_last_activity.php",
   success:function()
   {

   }
  })
 }

 function make_chat_dialog_box(to_user_id, to_user_name)
 {
  var modal_content = '<div id="user_dialog_'+to_user_id+'" class="user_dialog" title="You have chat with '+to_user_name+'">';
  modal_content += '<div style="height:400px; border:1px solid #ccc; overflow-y: scroll; margin-bottom:24px; padding:16px;" class="chat_history" data-touserid="'+to_user_id+'" id="chat_history_'+to_user_id+'">';
  modal_content += '</div>';
  modal_content += '<div class="form-group">';
  modal_content += '<textarea name="chat_message_'+to_user_id+'" id="chat_message_'+to_user_id+'" class="form-control"></textarea>';
  modal_content += '</div><div class="form-group" align="right">';
  modal_content+= '<button type="button" name="send_chat" id="'+to_user_id+'" class="btn btn-info send_chat">Send</button></div></div>';
  $('#user_model_details').html(modal_content);
 }

 $(document).on('click', '.start_chat', function(){
  var to_user_id = $(this).data('touserid');
  var to_user_name = $(this).data('tousername');
  make_chat_dialog_box(to_user_id, to_user_name);
  $("#user_dialog_"+to_user_id).dialog({
   autoOpen:false,
   width:400
  });
  $('#user_dialog_'+to_user_id).dialog('open');
 });

 $(document).on('click', '.send_chat', function(){
  var to_user_id = $(this).attr('id');
  var chat_message = $('#chat_message_'+to_user_id).val();
  $.ajax({
   url:"insert_chat.php",
   method:"POST",
   data:{to_user_id:to_user_id, chat_message:chat_message},
   success:function(data)
   {
    $('#chat_message_'+to_user_id).val('');
    $('#chat_history_'+to_user_id).html(data);
   }
  })
 });
 
});  
</script>

Here in index.php page we have write jquery script on send button which class is .send_chat as selector. So when we have click on send button in chat dialog box then it will execute this block of code. In this script we have fetch value of id attribute of this send button in which we have store user id to whom we have send message. After this we have fetch value of textarea in which we have write chat message. After this we have send ajax request to insert_chat.php page for insert chat message into mysql database. This page source code we can find below.


<?php

//insert_chat.php

include('database_connection.php');

session_start();

$data = array(
 ':to_user_id'  => $_POST['to_user_id'],
 ':from_user_id'  => $_SESSION['user_id'],
 ':chat_message'  => $_POST['chat_message'],
 ':status'   => '1'
);

$query = "
INSERT INTO chat_message 
(to_user_id, from_user_id, chat_message, status) 
VALUES (:to_user_id, :from_user_id, :chat_message, :status)
";

$statement = $connect->prepare($query);

if($statement->execute($data))
{
 echo fetch_user_chat_history($_SESSION['user_id'], $_POST['to_user_id'], $connect);
}

?>


Above source code for insert chat message into Mysql table. Here we have make simple insert query using PHP PDO and pass required data for insert into database. After insert into database we want to display all chat message conversation in chat dialog box. So we have to fetch chat data from database which source code we can find below.


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=chat", "root", "");

date_default_timezone_set('Asia/Kolkata');

function fetch_user_last_activity($user_id, $connect)
{
 $query = "
 SELECT * FROM login_details 
 WHERE user_id = '$user_id' 
 ORDER BY last_activity DESC 
 LIMIT 1
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  return $row['last_activity'];
 }
}

function fetch_user_chat_history($from_user_id, $to_user_id, $connect)
{
 $query = "
 SELECT * FROM chat_message 
 WHERE (from_user_id = '".$from_user_id."' 
 AND to_user_id = '".$to_user_id."') 
 OR (from_user_id = '".$to_user_id."' 
 AND to_user_id = '".$from_user_id."') 
 ORDER BY timestamp DESC
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '<ul class="list-unstyled">';
 foreach($result as $row)
 {
  $user_name = '';
  if($row["from_user_id"] == $from_user_id)
  {
   $user_name = '<b class="text-success">You</b>';
  }
  else
  {
   $user_name = '<b class="text-danger">'.get_user_name($row['from_user_id'], $connect).'</b>';
  }
  $output .= '
  <li style="border-bottom:1px dotted #ccc">
   <p>'.$user_name.' - '.$row["chat_message"].'
    <div align="right">
     - <small><em>'.$row['timestamp'].'</em></small>
    </div>
   </p>
  </li>
  ';
 }
 $output .= '</ul>';
 return $output;
}

function get_user_name($user_id, $connect)
{
 $query = "SELECT username FROM login WHERE user_id = '$user_id'";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  return $row['username'];
 }
}



?>


For fetch chat conversation we have make fetch_user_chat_history() function in database_connection.php file. This function has fetch latest chat message from mysql database and return data in html format. Here we have make one another function get_user_name() this function has return username of particular user based on value of user_id. So, this two function has use for return chat message in html format and this data has been display under chat dialog box using Ajax. So, this way we have insert chat message into mysql database and then after display in chat dialog box using Ajax with PHP.

Auto Refresh Chat Message in PHP Chat Application




Once chat message has inserted into Mysql database then after we want to display chat message to sender and receiver in their chat history without refresh of web page. For this we have make two jquery function on index.php page. Below you can find source code of it.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header("location:login.php");
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   
   <div class="table-responsive">
    <h4 align="center">Online User</h4>
    <p align="right">Hi - <?php echo $_SESSION['username'];  ?> - <a href="logout.php">Logout</a></p>
    <div id="user_details"></div>
    <div id="user_model_details"></div>
   </div>
  </div>
    </body>  
</html>  




<script>  
$(document).ready(function(){

 fetch_user();

 setInterval(function(){
  update_last_activity();
  fetch_user();
  update_chat_history_data();
 }, 5000);

 function fetch_user()
 {
  $.ajax({
   url:"fetch_user.php",
   method:"POST",
   success:function(data){
    $('#user_details').html(data);
   }
  })
 }

 function update_last_activity()
 {
  $.ajax({
   url:"update_last_activity.php",
   success:function()
   {

   }
  })
 }

 function make_chat_dialog_box(to_user_id, to_user_name)
 {
  var modal_content = '<div id="user_dialog_'+to_user_id+'" class="user_dialog" title="You have chat with '+to_user_name+'">';
  modal_content += '<div style="height:400px; border:1px solid #ccc; overflow-y: scroll; margin-bottom:24px; padding:16px;" class="chat_history" data-touserid="'+to_user_id+'" id="chat_history_'+to_user_id+'">';
  modal_content += fetch_user_chat_history(to_user_id);
  modal_content += '</div>';
  modal_content += '<div class="form-group">';
  modal_content += '<textarea name="chat_message_'+to_user_id+'" id="chat_message_'+to_user_id+'" class="form-control"></textarea>';
  modal_content += '</div><div class="form-group" align="right">';
  modal_content+= '<button type="button" name="send_chat" id="'+to_user_id+'" class="btn btn-info send_chat">Send</button></div></div>';
  $('#user_model_details').html(modal_content);
 }

 $(document).on('click', '.start_chat', function(){
  var to_user_id = $(this).data('touserid');
  var to_user_name = $(this).data('tousername');
  make_chat_dialog_box(to_user_id, to_user_name);
  $("#user_dialog_"+to_user_id).dialog({
   autoOpen:false,
   width:400
  });
  $('#user_dialog_'+to_user_id).dialog('open');
 });

 $(document).on('click', '.send_chat', function(){
  var to_user_id = $(this).attr('id');
  var chat_message = $('#chat_message_'+to_user_id).val();
  $.ajax({
   url:"insert_chat.php",
   method:"POST",
   data:{to_user_id:to_user_id, chat_message:chat_message},
   success:function(data)
   {
    $('#chat_message_'+to_user_id).val('');
    $('#chat_history_'+to_user_id).html(data);
   }
  })
 });

 function fetch_user_chat_history(to_user_id)
 {
  $.ajax({
   url:"fetch_user_chat_history.php",
   method:"POST",
   data:{to_user_id:to_user_id},
   success:function(data){
    $('#chat_history_'+to_user_id).html(data);
   }
  })
 }

 function update_chat_history_data()
 {
  $('.chat_history').each(function(){
   var to_user_id = $(this).data('touserid');
   fetch_user_chat_history(to_user_id);
  });
 }

 $(document).on('click', '.ui-button-icon', function(){
  $('.user_dialog').dialog('destroy').remove();
 });
 
});  
</script>


Above we can see we have make two function like fetch_user_chat_history() and update_chat_history_data() function. First function fetch chat data from mysql table and display under chat history div tag of particular user dialog box. After this we have called this function into make_chat_dialog_box(). So when user click on start chat button then it will called make_chat_dialog_box() function for make dynamic chat dialog box and under this function will called fetch_user_chat_history() which fetch chat message of sender and receiver and display under chat dialog box chat history div tag.

For make live and real time chat application we have make update_chat_history_data() function, this function we have use each() jquery method on .chat_history div tag. So this method will fetch data-touserid of each div tag of this class and store under this to_user_id variable and then after it will called fetch_user_chat_history() function based on value of to_user_id variable. So this function will update chat history in all chat dialog box which we have open in web page. For live and real time chat system we have add this update_chat_history_data() function into setInterval() method. So this function will be executed on every 5 seconds and it will update chat history data on every 5 seconds on web page in each user chat dialog box.


<?php

//fetch_user_chat_history.php

include('database_connection.php');

session_start();

echo fetch_user_chat_history($_SESSION['user_id'], $_POST['to_user_id'], $connect);

?>


Above code has been executed when ajax request send request to this page. Here we have simply called fetch_chat_history() function which we have make under database_connection.php. This function will fetch sender and receiver chat data and converted into html format and send to Ajax request.




Make New Message Notification in Chat Application


When sender send chat message to receiver then at receiver web page new message notification must be display and display how many new message he has received. So this feature we have add into this PHP Ajax Chat Application. For this we have make one function in database_connection.php file which source code you can find below.


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=chat", "root", "");

date_default_timezone_set('Asia/Kolkata');

function fetch_user_last_activity($user_id, $connect)
{
 $query = "
 SELECT * FROM login_details 
 WHERE user_id = '$user_id' 
 ORDER BY last_activity DESC 
 LIMIT 1
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  return $row['last_activity'];
 }
}

function fetch_user_chat_history($from_user_id, $to_user_id, $connect)
{
 $query = "
 SELECT * FROM chat_message 
 WHERE (from_user_id = '".$from_user_id."' 
 AND to_user_id = '".$to_user_id."') 
 OR (from_user_id = '".$to_user_id."' 
 AND to_user_id = '".$from_user_id."') 
 ORDER BY timestamp DESC
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '<ul class="list-unstyled">';
 foreach($result as $row)
 {
  $user_name = '';
  if($row["from_user_id"] == $from_user_id)
  {
   $user_name = '<b class="text-success">You</b>';
  }
  else
  {
   $user_name = '<b class="text-danger">'.get_user_name($row['from_user_id'], $connect).'</b>';
  }
  $output .= '
  <li style="border-bottom:1px dotted #ccc">
   <p>'.$user_name.' - '.$row["chat_message"].'
    <div align="right">
     - <small><em>'.$row['timestamp'].'</em></small>
    </div>
   </p>
  </li>
  ';
 }
 $output .= '</ul>';
 $query = "
 UPDATE chat_message 
 SET status = '0' 
 WHERE from_user_id = '".$to_user_id."' 
 AND to_user_id = '".$from_user_id."' 
 AND status = '1'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 return $output;
}

function get_user_name($user_id, $connect)
{
 $query = "SELECT username FROM login WHERE user_id = '$user_id'";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  return $row['username'];
 }
}

function count_unseen_message($from_user_id, $to_user_id, $connect)
{
 $query = "
 SELECT * FROM chat_message 
 WHERE from_user_id = '$from_user_id' 
 AND to_user_id = '$to_user_id' 
 AND status = '1'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $count = $statement->rowCount();
 $output = '';
 if($count > 0)
 {
  $output = '<span class="label label-success">'.$count.'</span>';
 }
 return $output;
}



?>


Above we can see count_unseen_message() function which get number chat message is unread under chat message table for particular user. Here status '1' means message unread and once message has been read then status will be change to '0'. So this function will count unread message of receiver of partcular sender based on value of status. For change message status we have add update chat message query under fetch_user_chat_history() so when this function will called then it will change chat message to '0'. After this function has been called in fetch_user.php where we have fetch user details. So, it will display new message notification when it has fetch user details. So on every user row it will display any new message notification or not.


<?php

//fetch_user.php

include('database_connection.php');

session_start();

$query = "
SELECT * FROM login 
WHERE user_id != '".$_SESSION['user_id']."' 
";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

$output = '
<table class="table table-bordered table-striped">
 <tr>
  <th>Username</th>
  <th>Status</th>
  <th>Action</th>
 </tr>
';

foreach($result as $row)
{
 $status = '';
 $current_timestamp = strtotime(date("Y-m-d H:i:s") . '- 10 second');
 $current_timestamp = date('Y-m-d H:i:s', $current_timestamp);
 $user_last_activity = fetch_user_last_activity($row['user_id'], $connect);
 if($user_last_activity > $current_timestamp)
 {
  $status = '<span class="label label-success">Online</span>';
 }
 else
 {
  $status = '<span class="label label-danger">Offline</span>';
 }
 $output .= '
 <tr>
  <td>'.$row['username'].' '.count_unseen_message($row['user_id'], $_SESSION['user_id'], $connect).'</td>
  <td>'.$status.'</td>
  <td><button type="button" class="btn btn-info btn-xs start_chat" data-touserid="'.$row['user_id'].'" data-tousername="'.$row['username'].'">Start Chat</button></td>
 </tr>
 ';
}

$output .= '</table>';

echo $output;

?>


Here Above we have called count_unseen_message() function for display any new message notification for every user. If there is any new message notification then it will display new chat message notification otherwise it will not display notification. So this way we can display new message notification in Chat Application by using PHP with Ajax JQuery with Mysql.

Display Typing Notification to Receiver When Sender Start Type




Here we have add one more in out chat application and that is how can we display typing notification to receiver when sender has start type in his chat dialog box. We have mainly seen this type of feature in many social media site. So, here we have also add this functionality in building of chat application using PHP Ajax. For this we have add one table column with name is_type in login_details table with enum('no','yes') datatype. No means user is not type in his chat dialog box and yes means user is start type in his chat dialog box. When user login into chat system then this column value will be no and we will update this column value to yes when user has start write in his chat dialog box.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header("location:login.php");
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   
   <div class="table-responsive">
    <h4 align="center">Online User</h4>
    <p align="right">Hi - <?php echo $_SESSION['username'];  ?> - <a href="logout.php">Logout</a></p>
    <div id="user_details"></div>
    <div id="user_model_details"></div>
   </div>
  </div>
    </body>  
</html>  




<script>  
$(document).ready(function(){

 fetch_user();

 setInterval(function(){
  update_last_activity();
  fetch_user();
  update_chat_history_data();
 }, 5000);

 function fetch_user()
 {
  $.ajax({
   url:"fetch_user.php",
   method:"POST",
   success:function(data){
    $('#user_details').html(data);
   }
  })
 }

 function update_last_activity()
 {
  $.ajax({
   url:"update_last_activity.php",
   success:function()
   {

   }
  })
 }

 function make_chat_dialog_box(to_user_id, to_user_name)
 {
  var modal_content = '<div id="user_dialog_'+to_user_id+'" class="user_dialog" title="You have chat with '+to_user_name+'">';
  modal_content += '<div style="height:400px; border:1px solid #ccc; overflow-y: scroll; margin-bottom:24px; padding:16px;" class="chat_history" data-touserid="'+to_user_id+'" id="chat_history_'+to_user_id+'">';
  modal_content += fetch_user_chat_history(to_user_id);
  modal_content += '</div>';
  modal_content += '<div class="form-group">';
  modal_content += '<textarea name="chat_message_'+to_user_id+'" id="chat_message_'+to_user_id+'" class="form-control chat_message"></textarea>';
  modal_content += '</div><div class="form-group" align="right">';
  modal_content+= '<button type="button" name="send_chat" id="'+to_user_id+'" class="btn btn-info send_chat">Send</button></div></div>';
  $('#user_model_details').html(modal_content);
 }

 $(document).on('click', '.start_chat', function(){
  var to_user_id = $(this).data('touserid');
  var to_user_name = $(this).data('tousername');
  make_chat_dialog_box(to_user_id, to_user_name);
  $("#user_dialog_"+to_user_id).dialog({
   autoOpen:false,
   width:400
  });
  $('#user_dialog_'+to_user_id).dialog('open');
 });

 $(document).on('click', '.send_chat', function(){
  var to_user_id = $(this).attr('id');
  var chat_message = $('#chat_message_'+to_user_id).val();
  $.ajax({
   url:"insert_chat.php",
   method:"POST",
   data:{to_user_id:to_user_id, chat_message:chat_message},
   success:function(data)
   {
    $('#chat_message_'+to_user_id).val('');
    $('#chat_history_'+to_user_id).html(data);
   }
  })
 });

 function fetch_user_chat_history(to_user_id)
 {
  $.ajax({
   url:"fetch_user_chat_history.php",
   method:"POST",
   data:{to_user_id:to_user_id},
   success:function(data){
    $('#chat_history_'+to_user_id).html(data);
   }
  })
 }

 function update_chat_history_data()
 {
  $('.chat_history').each(function(){
   var to_user_id = $(this).data('touserid');
   fetch_user_chat_history(to_user_id);
  });
 }

 $(document).on('click', '.ui-button-icon', function(){
  $('.user_dialog').dialog('destroy').remove();
 });

 $(document).on('focus', '.chat_message', function(){
  var is_type = 'yes';
  $.ajax({
   url:"update_is_type_status.php",
   method:"POST",
   data:{is_type:is_type},
   success:function()
   {

   }
  })
 });

 $(document).on('blur', '.chat_message', function(){
  var is_type = 'no';
  $.ajax({
   url:"update_is_type_status.php",
   method:"POST",
   data:{is_type:is_type},
   success:function()
   {
    
   }
  })
 });
 
});  
</script>


First we have on index.php page make_chat_dialog_box() function and in this function we have add .chat_message in the class attribute of textarea field. We will use this class attribute as a selector in jquery script. After this we have use this selector with jquery focus and blur event. Focus event means when cursor come into textarea field then this focus event code will execute at that time is_type variable value is equal to yes and this variable we have send to ajax request for update is_type table column value to yes. And on blur event when cursor leave from textarea field and at that time is_type variable value set to not and send this variable to ajax request for update is_type table column value set to no in PHP script.


<?php

//update_is_type_status.php

include('database_connection.php');

session_start();

$query = "
UPDATE login_details 
SET is_type = '".$_POST["is_type"]."' 
WHERE login_details_id = '".$_SESSION["login_details_id"]."'
";

$statement = $connect->prepare($query);

$statement->execute();

?>


This update_is_type_status.php page has received two ajax request at textarea field focus event and second request on textarea field blur event. In both event request has been send to this page for update value of is_type table column of login_details table. Now we want to fetch when particular user login_details table is_status column value is yes which source code we can find below.


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=chat", "root", "");

date_default_timezone_set('Asia/Kolkata');

function fetch_user_last_activity($user_id, $connect)
{
 $query = "
 SELECT * FROM login_details 
 WHERE user_id = '$user_id' 
 ORDER BY last_activity DESC 
 LIMIT 1
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  return $row['last_activity'];
 }
}

function fetch_user_chat_history($from_user_id, $to_user_id, $connect)
{
 $query = "
 SELECT * FROM chat_message 
 WHERE (from_user_id = '".$from_user_id."' 
 AND to_user_id = '".$to_user_id."') 
 OR (from_user_id = '".$to_user_id."' 
 AND to_user_id = '".$from_user_id."') 
 ORDER BY timestamp DESC
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '<ul class="list-unstyled">';
 foreach($result as $row)
 {
  $user_name = '';
  if($row["from_user_id"] == $from_user_id)
  {
   $user_name = '<b class="text-success">You</b>';
  }
  else
  {
   $user_name = '<b class="text-danger">'.get_user_name($row['from_user_id'], $connect).'</b>';
  }
  $output .= '
  <li style="border-bottom:1px dotted #ccc">
   <p>'.$user_name.' - '.$row["chat_message"].'
    <div align="right">
     - <small><em>'.$row['timestamp'].'</em></small>
    </div>
   </p>
  </li>
  ';
 }
 $output .= '</ul>';
 $query = "
 UPDATE chat_message 
 SET status = '0' 
 WHERE from_user_id = '".$to_user_id."' 
 AND to_user_id = '".$from_user_id."' 
 AND status = '1'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 return $output;
}

function get_user_name($user_id, $connect)
{
 $query = "SELECT username FROM login WHERE user_id = '$user_id'";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  return $row['username'];
 }
}

function count_unseen_message($from_user_id, $to_user_id, $connect)
{
 $query = "
 SELECT * FROM chat_message 
 WHERE from_user_id = '$from_user_id' 
 AND to_user_id = '$to_user_id' 
 AND status = '1'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $count = $statement->rowCount();
 $output = '';
 if($count > 0)
 {
  $output = '<span class="label label-success">'.$count.'</span>';
 }
 return $output;
}

function fetch_is_type_status($user_id, $connect)
{
 $query = "
 SELECT is_type FROM login_details 
 WHERE user_id = '".$user_id."' 
 ORDER BY last_activity DESC 
 LIMIT 1
 "; 
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '';
 foreach($result as $row)
 {
  if($row["is_type"] == 'yes')
  {
   $output = ' - <small><em><span class="text-muted">Typing...</span></em></small>';
  }
 }
 return $output;
}



?>


On database_connection.php file we have make one another function for fetch user typing status for this we have make fetch_is_type_status() function. This function will return value if particular user is_type table column value is yes. If any user is_type table column value is yes then we want to display on webpage.


<?php

//fetch_user.php

include('database_connection.php');

session_start();

$query = "
SELECT * FROM login 
WHERE user_id != '".$_SESSION['user_id']."' 
";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

$output = '
<table class="table table-bordered table-striped">
 <tr>
  <th width="70%">Username</td>
  <th width="20%">Status</td>
  <th width="10%">Action</td>
 </tr>
';

foreach($result as $row)
{
 $status = '';
 $current_timestamp = strtotime(date("Y-m-d H:i:s") . '- 10 second');
 $current_timestamp = date('Y-m-d H:i:s', $current_timestamp);
 $user_last_activity = fetch_user_last_activity($row['user_id'], $connect);
 if($user_last_activity > $current_timestamp)
 {
  $status = '<span class="label label-success">Online</span>';
 }
 else
 {
  $status = '<span class="label label-danger">Offline</span>';
 }
 $output .= '
 <tr>
  <td>'.$row['username'].' '.count_unseen_message($row['user_id'], $_SESSION['user_id'], $connect).' '.fetch_is_type_status($row['user_id'], $connect).'</td>
  <td>'.$status.'</td>
  <td><button type="button" class="btn btn-info btn-xs start_chat" data-touserid="'.$row['user_id'].'" data-tousername="'.$row['username'].'">Start Chat</button></td>
 </tr>
 ';
}

$output .= '</table>';

echo $output;

?>


For display sender typing message notification to receiver for this we have called fetch_is_type_status() function in fetch_user.php page along with display of username table column. This page send updated user data on every 5 seconds. So, on every 5 seconds this function will be called and it will display updated status on web page. So, this is the whole process for display sender typing notification on receiver web page. This will add additional functionality in our chat application.

If have learn How to create Chat application in PHP with Ajax JQuery Mysql Bootstrap and Jquery UI from this tutorial. If you have any query into tutorial, please comment your query in comment box. We will reply on that comment and solve any issue in this real time live chat application using PHP Ajax.

Insert Emoji in Chat Message





Here we have add one more feature in PHP Chat application tutorial and this feature is how to insert Emoji in textarea field of chat message and emoji insert into mysql database and fetch emoji from Mysql database and display on web page using PHP with Ajax JQuery. For Insert Emoji into Mysql database, so first we have want to configured our mysql database for insert emoji into database. If we have not configured database then emoji will be converted into special character. For configured Mysql database, so first we have to change collation of Mysql database from default to uft8mb4_bin. For this we have to write following SQL query.


ALTER DATABASE chat CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;


Above query will change default of collation of Mysql database to utf8mb4_bin. Same way we want to also change collation of table in which want to store emoji with chat message. For this we have to write below sql query.


ALTER TABLE chat_message CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin


The Above query will change default collation of chat_message table to utf8mb4_bin. This is required for store emoji under Mysql database. After this we want to add character set in database connection also. For this we have to go to database_connection.php file and define character set in database connection string.


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=chat;charset=utf8mb4", "root", "");


So this way we can define character set under database connection string. This way we can configured our Mysql database for insert emoji under Mysql database table. Now we have proceed for how to use emoji in our PHP application. For emoji use in our web application we have use emojioneArea plugin. By using this plugin we can use emoji in our PHP web application. Below you can find index.php file code in which we have integrate emojioneArea plugin.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header("location:login.php");
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://cdn.rawgit.com/mervick/emojionearea/master/dist/emojionearea.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script src="https://cdn.rawgit.com/mervick/emojionearea/master/dist/emojionearea.min.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   
   <div class="table-responsive">
    <h4 align="center">Online User</h4>
    <p align="right">Hi - <?php echo $_SESSION['username'];  ?> - <a href="logout.php">Logout</a></p>
    <div id="user_details"></div>
    <div id="user_model_details"></div>
   </div>
  </div>
    </body>  
</html>  




<script>  
$(document).ready(function(){

 fetch_user();

 setInterval(function(){
  update_last_activity();
  fetch_user();
  update_chat_history_data();
 }, 5000);

 function fetch_user()
 {
  $.ajax({
   url:"fetch_user.php",
   method:"POST",
   success:function(data){
    $('#user_details').html(data);
   }
  })
 }

 function update_last_activity()
 {
  $.ajax({
   url:"update_last_activity.php",
   success:function()
   {

   }
  })
 }

 function make_chat_dialog_box(to_user_id, to_user_name)
 {
  var modal_content = '<div id="user_dialog_'+to_user_id+'" class="user_dialog" title="You have chat with '+to_user_name+'">';
  modal_content += '<div style="height:400px; border:1px solid #ccc; overflow-y: scroll; margin-bottom:24px; padding:16px;" class="chat_history" data-touserid="'+to_user_id+'" id="chat_history_'+to_user_id+'">';
  modal_content += fetch_user_chat_history(to_user_id);
  modal_content += '</div>';
  modal_content += '<div class="form-group">';
  modal_content += '<textarea name="chat_message_'+to_user_id+'" id="chat_message_'+to_user_id+'" class="form-control chat_message"></textarea>';
  modal_content += '</div><div class="form-group" align="right">';
  modal_content+= '<button type="button" name="send_chat" id="'+to_user_id+'" class="btn btn-info send_chat">Send</button></div></div>';
  $('#user_model_details').html(modal_content);
 }

 $(document).on('click', '.start_chat', function(){
  var to_user_id = $(this).data('touserid');
  var to_user_name = $(this).data('tousername');
  make_chat_dialog_box(to_user_id, to_user_name);
  $("#user_dialog_"+to_user_id).dialog({
   autoOpen:false,
   width:400
  });
  $('#user_dialog_'+to_user_id).dialog('open');
  $('#chat_message_'+to_user_id).emojioneArea({
   pickerPosition:"top",
   toneStyle: "bullet"
  });
 });

 $(document).on('click', '.send_chat', function(){
  var to_user_id = $(this).attr('id');
  var chat_message = $('#chat_message_'+to_user_id).val();
  $.ajax({
   url:"insert_chat.php",
   method:"POST",
   data:{to_user_id:to_user_id, chat_message:chat_message},
   success:function(data)
   {
    //$('#chat_message_'+to_user_id).val('');
    var element = $('#chat_message_'+to_user_id).emojioneArea();
    element[0].emojioneArea.setText('');
    $('#chat_history_'+to_user_id).html(data);
   }
  })
 });

 function fetch_user_chat_history(to_user_id)
 {
  $.ajax({
   url:"fetch_user_chat_history.php",
   method:"POST",
   data:{to_user_id:to_user_id},
   success:function(data){
    $('#chat_history_'+to_user_id).html(data);
   }
  })
 }

 function update_chat_history_data()
 {
  $('.chat_history').each(function(){
   var to_user_id = $(this).data('touserid');
   fetch_user_chat_history(to_user_id);
  });
 }

 $(document).on('click', '.ui-button-icon', function(){
  $('.user_dialog').dialog('destroy').remove();
 });

 $(document).on('focus', '.chat_message', function(){
  var is_type = 'yes';
  $.ajax({
   url:"update_is_type_status.php",
   method:"POST",
   data:{is_type:is_type},
   success:function()
   {

   }
  })
 });

 $(document).on('blur', '.chat_message', function(){
  var is_type = 'no';
  $.ajax({
   url:"update_is_type_status.php",
   method:"POST",
   data:{is_type:is_type},
   success:function()
   {
    
   }
  })
 });
 
});  
</script>


Above we can see how to use emojioneArea plugin, so first we have imported emojioneArea plugin stylesheet and javascript file in above of this page. Now we want to initialize emojioneArea plugin on textarea field of chat dialog box in which we have type chat message. So, in jquery code on .start_chat click event and in this we have initialize emojioneArea plugin by using emojioneArea() method. This method will initialize this plugin when we have click on start chat button then this plugin will activate and we can on textarea field. After send of message we want to clear textarea field text with emoji, so we have use use emojioneArea.setText(''), by using this method we can clear emoji with text from textarea field. So this way we can use emoji in our PHP Chat application.

Group Chat





This simple one to one chat application which we have build still, but now we have add Group Chat feature also in Chat System. By using Group chat all user can communicate with each other in one single place at the same time and all user can see message of all user in Group Chat window. So, Below you can find step by step source of Group Chat which we have integrate in our exisiting chat application.



<!--
index.php
!-->

<div id="group_chat_dialog" title="Group Chat Window">
 <div id="group_chat_history" style="height:400px; border:1px solid #ccc; overflow-y: scroll; margin-bottom:24px; padding:16px;">

 </div>
 <div class="form-group">
  <textarea name="group_chat_message" id="group_chat_message" class="form-control"></textarea>
 </div>
 <div class="form-group" align="right">
  <button type="button" name="send_group_chat" id="send_group_chat" class="btn btn-info">Send</button>
 </div>
</div>


Here first we have make Group Chat dialog box by using Jquery UI dialog plugin which source code you have find above in index.php file.



<!--
index.php
!-->

$('#group_chat_dialog').dialog({
 autoOpen:false,
 width:400
});


This code will activate jQuery UI dialog plugin on #group_chat_dialog div tag and autoOpen option set to false means it will not pop up dialog box on page load.



<!--
index.php
!-->

<input type="hidden" id="is_active_group_chat_window" value="no" />
<button type="button" name="group_chat" id="group_chat" class="btn btn-warning btn-xs">Group Chat</button>


Here we have define one button, when we have click on group_chat button then we want to pop up Group Chat dialog box on web page. Here we have also define one hidden field with id = is_active_group_chat_window. This field value we have set to no that means Group chat dialog box is not open on web page. This field value will be change to yes if Group chat has been pop up on web page.



<!--
index.php
!-->

$('#group_chat').click(function(){
 $('#group_chat_dialog').dialog('open');
 $('#is_active_group_chat_window').val('yes');
 fetch_group_chat_history();
});


For pop up group chat dialog box we have write above jquery code on button with id=group_chat. For pop up group chat dialog box we have use .dialog('open') method. After pop up of group chat box we have change hidden field value to 'yes' and here we have called fetch_group_chat_history() function which will fetch group chat message and display under group chat dialog box. This function source code you can find below.



<!--
index.php
!-->

$('#send_group_chat').click(function(){
 var chat_message = $('#group_chat_message').val();
 var action = 'insert_data';
 if(chat_message != '')
 {
  $.ajax({
   url:"group_chat.php",
   method:"POST",
   data:{chat_message:chat_message, action:action},
   success:function(data){
    $('#group_chat_message').val('');
    $('#group_chat_history').html(data);
   }
  })
 }
});


Above code is for insert chat message into Group chat. For this here we have use Ajax request, by using Ajax request we have send request to PHP script for insert chat message into Mysql table. Here we have send request to group_chat.php file.



<!--
index.php
!-->

function fetch_group_chat_history()
{
 var group_chat_dialog_active = $('#is_active_group_chat_window').val();
 var action = "fetch_data";
 if(group_chat_dialog_active == 'yes')
 {
  $.ajax({
   url:"group_chat.php",
   method:"POST",
   data:{action:action},
   success:function(data)
   {
    $('#group_chat_history').html(data);
   }
  })
 }
}


For fetch all group chat message here we have make one jquery function which use Ajax request for fetch Group chat message from Mysql database and display under Group Chat dialog box. Here also ajax request has been send to group_chat.php file.


<?php

//group_chat.php

include('database_connection.php');

session_start();

if($_POST["action"] == "insert_data")
{
 $data = array(
  ':from_user_id'  => $_SESSION["user_id"],
  ':chat_message'  => $_POST['chat_message'],
  ':status'   => '1'
 );

 $query = "
 INSERT INTO chat_message 
 (from_user_id, chat_message, status) 
 VALUES (:from_user_id, :chat_message, :status)
 ";

 $statement = $connect->prepare($query);

 if($statement->execute($data))
 {
  echo fetch_group_chat_history($connect);
 }

}

if($_POST["action"] == "fetch_data")
{
 echo fetch_group_chat_history($connect);
}

?>


This is source code of group_chat.php file. Here we have perform two database operation. If $_POST["action"] == 'insert_data', then that block of code will insert group chat message into Mysql table and if $_POST["action"] == 'fetch_data' then that block of code will fetch all group chat message from Mysql database. For fetch group chat message we have make one php function like fetch_group_chat_history($connect) in database_connection.php file.


<?php

//database_connection.php

function fetch_group_chat_history($connect)
{
 $query = "
 SELECT * FROM chat_message 
 WHERE to_user_id = '0'  
 ORDER BY timestamp DESC
 ";

 $statement = $connect->prepare($query);

 $statement->execute();

 $result = $statement->fetchAll();

 $output = '<ul class="list-unstyled">';
 foreach($result as $row)
 {
  $user_name = '';
  if($row["from_user_id"] == $_SESSION["user_id"])
  {
   $user_name = '<b class="text-success">You</b>';
  }
  else
  {
   $user_name = '<b class="text-danger">'.get_user_name($row['from_user_id'], $connect).'</b>';
  }

  $output .= '

  <li style="border-bottom:1px dotted #ccc">
   <p>'.$user_name.' - '.$row['chat_message'].' 
    <div align="right">
     - <small><em>'.$row['timestamp'].'</em></small>
    </div>
   </p>
  </li>
  ';
 }
 $output .= '</ul>';
 return $output;
}

?>

Above source code is from database_connection.php file php function fetch_group_chat_history($connect). This function return fetch all group chat message.


<!--

index.php

!-->

setInterval(function(){
 update_last_activity();
 fetch_user();
 update_chat_history_data();
 fetch_group_chat_history();
}, 5000);


For make group chat in real time then we have called jquery fetch_group_chat_history() function in setInterval() method in which fetch_group_chat_history() run on every 5 seconds and it will make Group chat feature in real time. So, this is step by step process of integrate Group chat feature in our exisiting chat application which has been made by using PHP with Ajax Jquery, Mysql and Bootstrap.

Image Share in Group Chat


After making Group Chat feature in Chat App, now we have add one more feature like image share in exisiting Chat application. So, Group user can share image in Group and that image can view by all member. For share image we have use Jquery Form plugin, by using this plugin we can share image in Group chat. Same way we have replace textarea field with editable div tag by using contenteditable attribute. By using this attribute we can make editable div tag for type chat message. And under this tag we will display uploaded image, so user can type message with image also. And by click on send button group member can share image in Group which will be visible to all member of group. Below you can find source code of How to share image in group chat of Chat application.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header("location:login.php");
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://cdn.rawgit.com/mervick/emojionearea/master/dist/emojionearea.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script src="https://cdn.rawgit.com/mervick/emojionearea/master/dist/emojionearea.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   <div class="row">
    <div class="col-md-8 col-sm-6">
     <h4>Online User</h4>
    </div>
    <div class="col-md-2 col-sm-3">
     <input type="hidden" id="is_active_group_chat_window" value="no" />
     <button type="button" name="group_chat" id="group_chat" class="btn btn-warning btn-xs">Group Chat</button>
    </div>
    <div class="col-md-2 col-sm-3">
     <p align="right">Hi - <?php echo $_SESSION['username']; ?> - <a href="logout.php">Logout</a></p>
    </div>
   </div>
   <div class="table-responsive">
    
    <div id="user_details"></div>
    <div id="user_model_details"></div>
   </div>
  </div>
    </body>  
</html>

<style>

.chat_message_area
{
 position: relative;
 width: 100%;
 height: auto;
 background-color: #FFF;
    border: 1px solid #CCC;
    border-radius: 3px;
}

#group_chat_message
{
 width: 100%;
 height: auto;
 min-height: 80px;
 overflow: auto;
 padding:6px 24px 6px 12px;
}

.image_upload
{
 position: absolute;
 top:3px;
 right:3px;
}
.image_upload > form > input
{
    display: none;
}

.image_upload img
{
    width: 24px;
    cursor: pointer;
}

</style>  

<div id="group_chat_dialog" title="Group Chat Window">
 <div id="group_chat_history" style="height:400px; border:1px solid #ccc; overflow-y: scroll; margin-bottom:24px; padding:16px;">

 </div>
 <div class="form-group">
  <!--<textarea name="group_chat_message" id="group_chat_message" class="form-control"></textarea>!-->
  <div class="chat_message_area">
   <div id="group_chat_message" contenteditable class="form-control">

   </div>
   <div class="image_upload">
    <form id="uploadImage" method="post" action="upload.php">
     <label for="uploadFile"><img src="upload.png" /></label>
     <input type="file" name="uploadFile" id="uploadFile" accept=".jpg, .png" />
    </form>
   </div>
  </div>
 </div>
 <div class="form-group" align="right">
  <button type="button" name="send_group_chat" id="send_group_chat" class="btn btn-info">Send</button>
 </div>
</div>


<script>  
$(document).ready(function(){

 fetch_user();

 setInterval(function(){
  update_last_activity();
  fetch_user();
  update_chat_history_data();
  fetch_group_chat_history();
 }, 5000);

 function fetch_user()
 {
  $.ajax({
   url:"fetch_user.php",
   method:"POST",
   success:function(data){
    $('#user_details').html(data);
   }
  })
 }

 function update_last_activity()
 {
  $.ajax({
   url:"update_last_activity.php",
   success:function()
   {

   }
  })
 }

 function make_chat_dialog_box(to_user_id, to_user_name)
 {
  var modal_content = '<div id="user_dialog_'+to_user_id+'" class="user_dialog" title="You have chat with '+to_user_name+'">';
  modal_content += '<div style="height:400px; border:1px solid #ccc; overflow-y: scroll; margin-bottom:24px; padding:16px;" class="chat_history" data-touserid="'+to_user_id+'" id="chat_history_'+to_user_id+'">';
  modal_content += fetch_user_chat_history(to_user_id);
  modal_content += '</div>';
  modal_content += '<div class="form-group">';
  modal_content += '<textarea name="chat_message_'+to_user_id+'" id="chat_message_'+to_user_id+'" class="form-control chat_message"></textarea>';
  modal_content += '</div><div class="form-group" align="right">';
  modal_content+= '<button type="button" name="send_chat" id="'+to_user_id+'" class="btn btn-info send_chat">Send</button></div></div>';
  $('#user_model_details').html(modal_content);
 }

 $(document).on('click', '.start_chat', function(){
  var to_user_id = $(this).data('touserid');
  var to_user_name = $(this).data('tousername');
  make_chat_dialog_box(to_user_id, to_user_name);
  $("#user_dialog_"+to_user_id).dialog({
   autoOpen:false,
   width:400
  });
  $('#user_dialog_'+to_user_id).dialog('open');
  $('#chat_message_'+to_user_id).emojioneArea({
   pickerPosition:"top",
   toneStyle: "bullet"
  });
 });

 $(document).on('click', '.send_chat', function(){
  var to_user_id = $(this).attr('id');
  var chat_message = $('#chat_message_'+to_user_id).val();
  $.ajax({
   url:"insert_chat.php",
   method:"POST",
   data:{to_user_id:to_user_id, chat_message:chat_message},
   success:function(data)
   {
    //$('#chat_message_'+to_user_id).val('');
    var element = $('#chat_message_'+to_user_id).emojioneArea();
    element[0].emojioneArea.setText('');
    $('#chat_history_'+to_user_id).html(data);
   }
  })
 });

 function fetch_user_chat_history(to_user_id)
 {
  $.ajax({
   url:"fetch_user_chat_history.php",
   method:"POST",
   data:{to_user_id:to_user_id},
   success:function(data){
    $('#chat_history_'+to_user_id).html(data);
   }
  })
 }

 function update_chat_history_data()
 {
  $('.chat_history').each(function(){
   var to_user_id = $(this).data('touserid');
   fetch_user_chat_history(to_user_id);
  });
 }

 $(document).on('click', '.ui-button-icon', function(){
  $('.user_dialog').dialog('destroy').remove();
  $('#is_active_group_chat_window').val('no');
 });

 $(document).on('focus', '.chat_message', function(){
  var is_type = 'yes';
  $.ajax({
   url:"update_is_type_status.php",
   method:"POST",
   data:{is_type:is_type},
   success:function()
   {

   }
  })
 });

 $(document).on('blur', '.chat_message', function(){
  var is_type = 'no';
  $.ajax({
   url:"update_is_type_status.php",
   method:"POST",
   data:{is_type:is_type},
   success:function()
   {
    
   }
  })
 });

 $('#group_chat_dialog').dialog({
  autoOpen:false,
  width:400
 });

 $('#group_chat').click(function(){
  $('#group_chat_dialog').dialog('open');
  $('#is_active_group_chat_window').val('yes');
  fetch_group_chat_history();
 });

 $('#send_group_chat').click(function(){
  var chat_message = $('#group_chat_message').html();
  var action = 'insert_data';
  if(chat_message != '')
  {
   $.ajax({
    url:"group_chat.php",
    method:"POST",
    data:{chat_message:chat_message, action:action},
    success:function(data){
     $('#group_chat_message').html('');
     $('#group_chat_history').html(data);
    }
   })
  }
 });

 function fetch_group_chat_history()
 {
  var group_chat_dialog_active = $('#is_active_group_chat_window').val();
  var action = "fetch_data";
  if(group_chat_dialog_active == 'yes')
  {
   $.ajax({
    url:"group_chat.php",
    method:"POST",
    data:{action:action},
    success:function(data)
    {
     $('#group_chat_history').html(data);
    }
   })
  }
 }

 $('#uploadFile').on('change', function(){
  $('#uploadImage').ajaxSubmit({
   target: "#group_chat_message",
   resetForm: true
  });
 });
 
});  
</script>



<?php

//upload.php

if(!empty($_FILES))
{
 if(is_uploaded_file($_FILES['uploadFile']['tmp_name']))
 {
  $_source_path = $_FILES['uploadFile']['tmp_name'];
  $target_path = 'upload/' . $_FILES['uploadFile']['name'];
  if(move_uploaded_file($_source_path, $target_path))
  {
   echo '<p><img src="'.$target_path.'" class="img-thumbnail" width="200" height="160" /></p><br />';
  }
 }
}

?>




Remove individual Chat Message




In this Ajax PHP Chat system we have add one more feature like how can user can remove their chat message from One to one chat. So, here we have add this functionality, so from chat from two person, sender user can remove his chat from chat history. In many social medial website we can see this type of feature. This feature is required, if user chat some mistake in chat message and post that message. This type of message can be removed by sender user. So that message will not be visible to receiver user.

For make this type of functionality under this system, first we have to put remove button with chat message. In this system in database_connection.php file, we have make one function fetch_user_chat_history(). This function has return chat history create between to user. In this function we have add remove chat message button. By click on this button particular user can remove his or her chat message. Below this you can find updated PHP code for fetch_user_chat_history() function.

database_connection.php

<?php

function fetch_user_chat_history($from_user_id, $to_user_id, $connect)
{
 $query = "
 SELECT * FROM chat_message 
 WHERE (from_user_id = '".$from_user_id."' 
 AND to_user_id = '".$to_user_id."') 
 OR (from_user_id = '".$to_user_id."' 
 AND to_user_id = '".$from_user_id."') 
 ORDER BY timestamp DESC
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '<ul class="list-unstyled">';
 foreach($result as $row)
 {
  $user_name = '';
  $dynamic_background = '';
  $chat_message = '';
  if($row["from_user_id"] == $from_user_id)
  {
   if($row["status"] == '2')
   {
    $chat_message = '<em>This message has been removed</em>';
    $user_name = '<b class="text-success">You</b>';
   }
   else
   {
    $chat_message = $row['chat_message'];
    $user_name = '<button type="button" class="btn btn-danger btn-xs remove_chat" id="'.$row['chat_message_id'].'">x</button>&nbsp;<b class="text-success">You</b>';
   }
   

   $dynamic_background = 'background-color:#ffe6e6;';
  }
  else
  {
   if($row["status"] == '2')
   {
    $chat_message = '<em>This message has been removed</em>';
   }
   else
   {
    $chat_message = $row["chat_message"];
   }
   $user_name = '<b class="text-danger">'.get_user_name($row['from_user_id'], $connect).'</b>';
   $dynamic_background = 'background-color:#ffffe6;';
  }
  $output .= '
  <li style="border-bottom:1px dotted #ccc;padding-top:8px; padding-left:8px; padding-right:8px;'.$dynamic_background.'">
   <p>'.$user_name.' - '.$chat_message.'
    <div align="right">
     - <small><em>'.$row['timestamp'].'</em></small>
    </div>
   </p>
  </li>
  ';
 }
 $output .= '</ul>';
 $query = "
 UPDATE chat_message 
 SET status = '0' 
 WHERE from_user_id = '".$to_user_id."' 
 AND to_user_id = '".$from_user_id."' 
 AND status = '1'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 return $output;
}

?>


Once remove chat button come with Chat history. After this we have to write Ajax Jquery code for send change status of particular chat message. So, on index.php we have write jQuery code, so when user click on remove chat button then this code will execute and this code will send ajax request to remove_chat.php file for change particular chat message status.

index.php

$(document).on('click', '.remove_chat', function(){
  var chat_message_id = $(this).attr('id');
  if(confirm("Are you sure you want to remove this chat?"))
  {
   $.ajax({
    url:"remove_chat.php",
    method:"POST",
    data:{chat_message_id:chat_message_id},
    success:function(data)
    {
     update_chat_history_data();
    }
   })
  }
 });


remove_chat.php

<?php

//remove_chat.php

include('database_connection.php');

if(isset($_POST["chat_message_id"]))
{
 $query = "
 UPDATE chat_message 
 SET status = '2' 
 WHERE chat_message_id = '".$_POST["chat_message_id"]."'
 ";

 $statement = $connect->prepare($query);

 $statement->execute();
}

?>


In above code we can see on index.php file we have add one more jQuery code for give action to remove chat button and in that code we have send Ajax request to remove_chat.php file for change status of chat message based on id value of chat message. This is whole process for add remove chat functionality in Live chat application using PHP Ajax jQuery and Mysql.

Remove Chat Message from Group Chat





After remove chat message from one to one chat history, then after in Chat Application, here we have add one more functionality like remove chat message from Group chat history also. Suppose user want to remove his chat message which he has post in Group then he can remove by using this feature. He can not only remove their message but also he can also remove image which he share into Group.

For implement this feature in existing Chat application we do not want to make huge changes in our existing PHP and jQuery code. First we do not want make any changes in index.php file. Which ever we have write jQuery code on .remove_chat button class, that code here we will also use for remove chat message from Group Chat history.

But we have make required changes in database_connection.php file fetch_group_chat_history(), because this function return Group chat history. So we have to make some changes under this function. Under this function we have to add remove chat button with chat message and this button must be visible to only that user who has share chat under group. Below you can find changes under function for fetch fetch group chat history.

database_connection.php

<?php

function fetch_group_chat_history($connect)
{
 $query = "
 SELECT * FROM chat_message 
 WHERE to_user_id = '0'  
 ORDER BY timestamp DESC
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '<ul class="list-unstyled">';
 foreach($result as $row)
 {
  $user_name = '';
  $chat_message = '';
  $dynamic_background = '';

  if($row['from_user_id'] == $_SESSION['user_id'])
  {
   if($row["status"] == '2')
   {
    $chat_message = '<em>This message has been removed</em>';
    $user_name = '<b class="text-success">You</b>';
   }
   else
   {
    $chat_message = $row['chat_message'];
    $user_name = '<button type="button" class="btn btn-danger btn-xs remove_chat" id="'.$row['chat_message_id'].'">x</button>&nbsp;<b class="text-success">You</b>';
   }
   $dynamic_background = 'background-color:#ffe6e6;';
  }
  else
  {
   if($row["status"] == '2')
   {
    $chat_message = '<em>This message has been removed</em>';
   }
   else
   {
    $chat_message = $row['chat_message'];
   }
   $user_name = '<b class="text-danger">'.get_user_name($row['from_user_id'], $connect).'</b>';
   $dynamic_background = 'background-color:#ffffe6;';
  }
  $output .= '
  <li style="border-bottom:1px dotted #ccc;padding-top:8px; padding-left:8px; padding-right:8px;'.$dynamic_background.'">
   <p>'.$user_name.' - '.$chat_message.' 
    <div align="right">
     - <small><em>'.$row['timestamp'].'</em></small>
    </div>
   </p>
   
  </li>
  ';
 }
 $output .= '</ul>';
 return $output;
}

?>


Registration in Chat application using PHP





Now our chat system core part is ready, so we want to make this system dynamic. That means new user can register into chat system and take part into chat with other member or group chat. For this we add new feature like new user registration in this PHP Ajax Chat application. By using this feature new use can register into this chat system and login into system and use this chat application different functionality like one to chat or group chat. This new register user can chat all member who has register into this system.

For make registration form for this chat application we have use simple HTML for front end and for backend we have use PHP script. Below you can find complete source code for Chat application registration using PHP.

register.php

<!--
//register.php
!-->

<?php

include('database_connection.php');

session_start();

$message = '';

if(isset($_SESSION['user_id']))
{
 header('location:index.php');
}

if(isset($_POST["register"]))
{
 $username = trim($_POST["username"]);
 $password = trim($_POST["password"]);
 $check_query = "
 SELECT * FROM login 
 WHERE username = :username
 ";
 $statement = $connect->prepare($check_query);
 $check_data = array(
  ':username'  => $username
 );
 if($statement->execute($check_data)) 
 {
  if($statement->rowCount() > 0)
  {
   $message .= '<p><label>Username already taken</label></p>';
  }
  else
  {
   if(empty($username))
   {
    $message .= '<p><label>Username is required</label></p>';
   }
   if(empty($password))
   {
    $message .= '<p><label>Password is required</label></p>';
   }
   else
   {
    if($password != $_POST['confirm_password'])
    {
     $message .= '<p><label>Password not match</label></p>';
    }
   }
   if($message == '')
   {
    $data = array(
     ':username'  => $username,
     ':password'  => password_hash($password, PASSWORD_DEFAULT)
    );

    $query = "
    INSERT INTO login 
    (username, password) 
    VALUES (:username, :password)
    ";
    $statement = $connect->prepare($query);
    if($statement->execute($data))
    {
     $message = "<label>Registration Completed</label>";
    }
   }
  }
 }
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   <div class="panel panel-default">
      <div class="panel-heading">Chat Application Register</div>
    <div class="panel-body">
     <form method="post">
      <span class="text-danger"><?php echo $message; ?></span>
      <div class="form-group">
       <label>Enter Username</label>
       <input type="text" name="username" class="form-control" />
      </div>
      <div class="form-group">
       <label>Enter Password</label>
       <input type="password" name="password" class="form-control" />
      </div>
      <div class="form-group">
       <label>Re-enter Password</label>
       <input type="password" name="confirm_password" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="register" class="btn btn-info" value="Register" />
      </div>
      <div align="center">
       <a href="login.php">Login</a>
      </div>
     </form>
    </div>
   </div>
  </div>
    </body>  
</html>



So, here in this chat application most of the feature has been covered and it is ready for any small project which has been use for any colleage project. If you have any new feature which has been required to add into this system, you can comment into comment box.

Remaining Source Code of Chat application in PHP using Ajax will be updated very soon.

175 comments:

  1. Hi sir! I have a minor problem but I think this is crucial. While loading the browser after pressing the log out the user table display the current account used as "online" too. For example, I have here 2 accounts "username1" & "username2" When I log in the "username1" it works all fine I can see if "username2" is online or not. But when I press logout the table also displays "username1 as online" which is the current account used to log in then after that the page performs the logout functionality. What should I do?

    ReplyDelete
  2. thank you so much for this tutorial

    ReplyDelete
  3. hello Sir

    can you send me file of this
    my email- rajibrp111@gmail.com

    ReplyDelete
  4. Send me project file of this email suryaprakash.ccc555@gmail.com

    ReplyDelete
  5. Hey, Admin
    Can you help me build on a Sports Betting Website. Am really stuck

    ReplyDelete
  6. Contact me through this mail -> lucaswarioba@gmail.com

    ReplyDelete
  7. sir thank you for your help!!!
    you're awesome,
    all things are working except status(online/offline) user remains offline
    while he is signed in, plz help me if its possible!!! thanks!!!!!!!!

    ReplyDelete
    Replies
    1. try to change timezone in database_connection.php

      Delete
    2. I have solved online and offline problem.

      Delete
    3. can you tell me how send me the code jawadkan.ins@gmail.conm

      Delete
    4. hai Sohel jaman how to solve the online and offline problem please share me

      Delete
    5. hai Sohel jaman how to solve the online and offline problem please share me

      Delete
    6. ********please help me, (online & offline) not work *********

      Delete
    7. Best option is to put timezone line in comment.
      Your systems will find your default timezone

      Delete
  8. Hi,

    Can you send me project file to this email jorgehelgueros@gmail.com please?

    Thanks

    ReplyDelete
  9. can you send me project file to my email yohanedevil1@gmail.com ?
    Thank you so much for the tutorial.

    ReplyDelete
  10. can you send me project file to my email redon.si10gta@gmail.com ?
    Thank you so much for the tutorial.

    ReplyDelete
  11. Thank you so much for the tutorial.

    ReplyDelete
  12. great sir. Sir can you mail me this project source code in my mail id
    khatriuttam85@gmail.com

    ReplyDelete
  13. sir please provide download zip file of Live Chat System in PHP using Ajax JQuery

    ReplyDelete
  14. provide zip file of Live Chat System in PHP using Ajax JQuery

    ReplyDelete
  15. Hi,

    Can you send me project file to this email juanes.iboy@gmail.com please?

    Thanks

    ReplyDelete
  16. Can you Pls share source code to santosh.cerdak@gmail.com

    ReplyDelete
  17. hello Sir

    can you send me file of this
    my email- devdharm9@gmail.com
    Thank you so much for the tutorial.

    ReplyDelete
  18. hello sir can you send me file of this
    emai shoaibansari78624@gnail.com

    ReplyDelete
  19. hello sir thank you por this post
    please send me source code at my email id 1sumitkmr0@gmail.com

    ReplyDelete
  20. Hi Sir,
    can you send methe project file to
    my email- ibrahimadiaw1997@gmail.com,
    And Thank you so much for the tutorial.

    ReplyDelete
  21. Hi Sir,
    can you send methe project file to
    my email- ibrahimadiaw1997@gmail.com,
    And Thank you so much for the tutorial.

    ReplyDelete
  22. Hi Sir,
    Can you send the project file to my email ibrahimadiaw1997@gmail.com
    And Thank you for the tutoriel

    ReplyDelete
  23. when someone is typing, everyone sees that person typing. it should only say typing next to the user that is being typed to. what is the fix for this?

    ReplyDelete
  24. hello sir
    can you send me file of this
    my email- aymenhamzaouir35@gmail.com
    Thank you so much for the tutorial.

    ReplyDelete
  25. hello Sir

    can you send me file of this
    my email- aymenhamzaouir35@gmail.com
    Thank you so much for the tutorial.

    ReplyDelete
  26. please send me code on mail
    mail id:- sriramkumar7277@gmail.com

    ReplyDelete
  27. send me source file to
    venkateshvoleti1995@gmail.com

    ReplyDelete
  28. Hi, all we have add source code download link under post, so check link and download source code and enjoy it.

    ReplyDelete
    Replies
    1. hi thank you so much for shearing the live chat code and i face problem user already login but shows offline how to solve please help me

      Delete
    2. Why conversion is top first?

      Delete
  29. hello sir why is that when i created new user I can't Log in

    ReplyDelete
    Replies
    1. In very short time we have add this feature into this application.

      Delete
  30. Why when I insert user it won't log in.

    ReplyDelete
  31. can i get the whole file (code) cons.timothy@gmail.com

    ReplyDelete
  32. hello...!
    can you send me this source app please?
    My email: layesall05@gmail.com

    ReplyDelete
  33. hi can have i file My eamil stephane92adannou@gmail.com

    ReplyDelete
  34. please tutor attach/send all file

    ReplyDelete
  35. online and offline are not working. now what can do? please help me. I have changed time zone but not working.

    ReplyDelete
  36. Hi Sir,
    Can you send the project file to my email dnabilah313@gmail.com
    And Thank you for the tutoriel

    ReplyDelete
  37. This is John. Tried the emoji codes but works only in text-window and not in the insert-chat window. Also Group chat is not working, too. Where can I download the complete files of your tutorial? or can you send the complete files to my email longroboteam@gmail.com

    ReplyDelete
    Replies
    1. pls send the complete file to this email wisdomayelsum@gmail.com

      Delete
  38. hello can you please send the project to my email jnrchimala@outlook.com

    ReplyDelete
  39. Hello!, thanks for the tutorial.
    but i think there should be a link to download this script.
    to save time anyway this is good.
    Please always make source code available via download link.

    ReplyDelete
  40. hello i have a problem what if i have more than hundred users and am using dataTable which display users in interval of 10. its is very difficult to chat with user number 18 Resistance because of refresh of whole page. please colud any one have any idea how to refresh only status.

    ReplyDelete
  41. so far am using codeigniter php framework so i have loaded the whole table from controller through ajax

    ReplyDelete
  42. sir can you please add timeline feature like fb where we can post status

    ReplyDelete
  43. its difficult to find right php code and data also .Please make it easy

    ReplyDelete
  44. That Was awesome, I am very very thanks full to you for this tutorials, can you please help me out with another thing? that will a big help of mine, what i am actually looking for to have sound to receiver when johnsmith send a message to the peter, if peter is active then the sound produce to in the peter box, now i have already build a project but it's sounds only on the johnsmith, is there any way? Thanks in advance,

    Love From Pakistan,

    ReplyDelete
  45. It was such a nice tutorial,

    ReplyDelete
  46. Hi I love your tutorial thank you for your sharing

    ReplyDelete
  47. Hello Sir Are You Have Versi MYSQLI NOT PDO..
    Please Help Me Sir

    ReplyDelete
  48. Hello dears, I have a problem when I login I reach this error (Fatal error: Call to undefined function password_verify() in C:\Program Files (x86)\EasyPHP-12.1\www\chat-application-using-php-ajax-jquery\login.php on line 38) I don't know why password_verify not working. it's very important for me can you please tell me how I can fix it.

    ReplyDelete
  49. the most confused tutorial ever, why there is sos much index files, and in video tutorial has not inlcuded sql side.

    ReplyDelete
  50. please provide download zip file of Live Chat System in PHP using Ajax JQuery

    ReplyDelete
  51. It nice tutorial.
    I have some problem, can't display emoji (display ??? )

    ReplyDelete
    Replies
    1. did you solved the emoji .. doenst working at all _
      this is what emoji display - ??? -

      Delete
    2. amigo. eu apenas tirei o chasetutf8 la do arquivo de conexao e funcionou.. estava com o mesmo problema

      Delete
    3. ALTER DATABASE chat CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;

      ALTER TABLE chat_message CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;

      Delete
  52. can you, plz mail me source code of live-chat-system-in-php-using-ajax-jquery

    ReplyDelete
  53. I cannot load images in group chat? Please Help Me.

    ReplyDelete
  54. it is very tutorial but can i also have the code?
    thank you and God Bless
    jvzsamson23@gmail.com

    ReplyDelete
  55. Hello sir can u send me file of ts to (pavan5639kumar@gmail.com)

    ReplyDelete
  56. wow!, nice job. thanks for the good effort so far.
    will be nice to add a video (and maybe other file types) upload.

    so each user can upload videos to his account and it can be viewed online and downloaded by other .
    thanks in advance.
    ikeminent4@yahoo.com

    ReplyDelete
  57. HICAN Y SHAR SOURCE CODE PLZ
    nebios@live.com

    ReplyDelete
  58. Thank you so much you save my time.

    ReplyDelete
    Replies
    1. Hi, can you please share the code with me? at tusharp98712@gmail.com
      Thank you!

      Delete
    2. pls send me the chat application using php ajax jquery project file to wisdomayelsum@gmail.com

      Delete
    3. sir pls if i login in using localhost i get Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ',' or ')' in C:\xampp\htdocs\blab\login.php on line 22 pls help me

      Delete
  59. Hi,
    1)How to disable adding emoji in message.
    2)How to send attachments

    ReplyDelete
  60. Can you send me the source code file please? ahmadsaeedbarakzay@gmail.com

    ReplyDelete
  61. hello please send me the code

    vamsiintegrity@gmail.com

    ReplyDelete
  62. hello sir very nice ji..can you
    pls send me this file of of my this mail id.
    nareshsonigodrej@gmail.com

    ReplyDelete
  63. Can you please send me the source files to

    soccer_tom@excite.com

    Thanks,
    Tom

    ReplyDelete
  64. Can you please send me all database used in this tutorial? Thank you so much
    kvldzc@gmail.com

    ReplyDelete
  65. Thank you so much.this is good.

    ReplyDelete
  66. hello sir can you send me all files on my email irakarama2019@gmail.com
    thank you to save our time

    ReplyDelete
  67. Thank you so much you save my time.

    ReplyDelete
  68. give source code faqnurul@gmail.com

    ReplyDelete
  69. hi can you share Source code plz

    ReplyDelete
  70. Sir, please, send me project file #mdmonirahmedsohan@gmail.com

    ReplyDelete
  71. it was so long .
    but very good .

    ReplyDelete
  72. Hi,

    I would really appreciate it if you can share the source code as a zip file with me via e-mail on dee.geentilal@gmail.com

    Many thanks!

    ReplyDelete
  73. Hi,

    Please can you share the source code via e-mail on dee.geentilal@gmail.com
    Many thanks

    ReplyDelete
  74. hello sir
    the tutorial is really helpful.
    could you please send me the project file at email id - ranmeet.singh72@gmail.com

    ReplyDelete
  75. Hello, I have problems with group chat.
    Can you send me project file to my email please?
    axa8xa8@gmail.com

    ReplyDelete
  76. I can't to make a notifications (with infos about new messages etc.) from browser when I minimalized it.
    I think that I should use window.addEventListener('blur', function(){//my new Notification function}, false);
    but without success.

    ReplyDelete
  77. Send me the file please..
    Thanks

    ReplyDelete
  78. The challenges I'm having is with the scrolling. It does not scroll automatically to last message when when I fetch history or send new message

    ReplyDelete
  79. what a mess did i do here please? Fatal error: Call to undefined function password_verify() in C:\wamp\www\one\login.php on line 36

    ReplyDelete
  80. what a mess did i do here please? Fatal error: Call to undefined function password_verify() in C:\wamp\www\one\login.php on line 36

    ReplyDelete
  81. Hi Sir I am shahbaz ,Can you share chat modules

    ReplyDelete
  82. ***idea***
    sort and display users according to the most recent sent message and also add a search field

    ReplyDelete
  83. Wow nice one, please send me all the source code

    ReplyDelete
  84. Tks so much much much from Vietnam, sir... it's very very very helpful, you'r awesomeee !!

    ReplyDelete
  85. Woow!!! what a great thing bt I have a fatal error in offline and online case.Please would you mind sending me the source code to kenedymuthui1@gmail.com

    ReplyDelete
  86. Cnn you please send me the full source code at m.haseebahad@gmail.com

    ReplyDelete
  87. Hello Sir,

    Can you please share the source code to me.

    ReplyDelete
  88. Hi Sir That Was So Use Full for Me But Have some Problem in Chat count So can you send Me that file On my email
    jayparmar181999@gmail.com

    ReplyDelete
  89. hi sir, how to do for two separate tables like chat with user and admin

    ReplyDelete
  90. Can you please send me the source code
    Email: reenorthcott@gmail.com

    ReplyDelete
  91. Bro can I have flowchart of this toturial?

    ReplyDelete
  92. hi sir can you please send the complete code my mail and mail id is sreevatsajutoor1993@gmail.com

    ReplyDelete
  93. Bonjour monsieur, pouvez-vous m'envoyer fichier code source sur mon gmail: cedricnamfoime@gmail.com / mbessem.12@gmail.com

    ReplyDelete
  94. Please send me a sql file.in
    Mail Id:- kcbuddhi27@gmail.com

    please sir,

    ReplyDelete
  95. Very good lesson. Charmed to found this tutorial
    This is needed in file insert_chat.php? :
    if($row["from_user_id"] == $from_user_id)
    { $user_name = . . . }
    else { $user_name = '. . .'.get_user_name($row['from_user_id'], $connect).'. . .'; }

    I think is not needed call get_user_name() function only $user_name = $to_user_id.
    If not me is the other, I d'ont tested but I think I rigth.

    ReplyDelete
  96. wow cool job!, can you, please mail me source code of live-chat-system-in-php-using-ajax-jquery, thks. rafael.lulet@gmail.com

    ReplyDelete
  97. Very Thanks for this splendid and best tutorial maked. I there are a Gram for the best turoial at the year sure I vote for this.

    ReplyDelete
  98. pls sir send me the project file of chat application using jquery to wisdomayelsum@gmail.com

    ReplyDelete
  99. after publishing on godadady it is not working... nd working fine in locally...
    wht would be the reason... sir.. plz help..

    ReplyDelete
  100. after publishing on godadady server it is not working ...

    in Locally it is working fine ?
    what would be the reason.. ?

    ReplyDelete
  101. Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home2/jsgufquj/public_html/pushnotify/login.php:5) in /home2/jsgufquj/public_html/pushnotify/login.php on line 9

    ReplyDelete
  102. ALTER DATABASE chat CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;


    Above query will change default of collation of Mysql database to utf8mb4_bin. Same way we want to also change collation of table in which want to store emoji with chat message. For this we have to write below sql query.


    ALTER TABLE chat_message CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin

    ReplyDelete
  103. One thing, on focus', '.chat_message', function() activate typing for all the users, for personalize I get the active user who recive the message:
    const to_user_id = $(this).attr('id');
    const to_usera_id = to_user_id.substr(to_user_id.length - 1);
    and only update the db for this user in login_details, instead to istyping with yes or not I make another column typeTo withe the proper value

    ReplyDelete
  104. for display if typin to me, change this:
    function fetch_is_type_status($user_id){
    $query = "SELECT typeto FROM login_details WHERE user_id = '$user_id' ORDER BY last_activity DESC LIMIT 1";
    $resultf=db_query($query);
    $row = $resultf->fetch_assoc();
    $output = '';
    // while($row = $resultf->fetch_assoc()){
    if($row["typeto"] == $_SESSION['user_id']){
    $output = ' typing';
    }

    ReplyDelete
  105. and this is better:
    $(document).on('blur', '.chat_message', function(){
    // var is_type = 'no';
    const to_usera_id = 0;
    $.ajax({
    url:"update_is_type_status.php",
    method:"POST",
    data:{toau:to_usera_id},
    success:function()
    {

    }
    })

    ReplyDelete
  106. No destroy all chats dialog, for this change this function:
    $(document).on('click', '.ui-button-icon', function(){
    const to_user_id = $(this).attr('id');
    const to_usera_id = to_user_id.substr(to_user_id.length - 1);
    $('#user_dialog_'+to_usera_id).dialog('destroy').remove();
    });

    ReplyDelete
  107. Thanks sir for your help . it is great app.
    Please, if possible when your time allows send me the code
    for the Chat application
    rakha400@hotmail.ccom

    ReplyDelete
  108. Hi Sir,

    Can you please send me the source code zip file to my email sulagna.bhattacharyaa@gmail.com

    ReplyDelete
  109. Hi Sir can you send me the source code in zip file in my email sulagna.bhattacharyaa@gmail.com

    ReplyDelete
  110. İf you have online/offline status problem thats code you can fixed

    //database_connection.php

    date_default_timezone_set('Time zone used by pc');


    //How it works
    Login = DateTimeNow(Default Timezone)
    İf(you pc time == date_default_timezone_set) status will work

    ReplyDelete
  111. Is it possible to add voice messaging option like as whatsapp. Thanks

    ReplyDelete
  112. can you, plz mail me source code of live-chat-system-in-php-using-ajax-jquery in my email:yahayzakria21@gmail.com

    ReplyDelete
  113. hello Sir
    can you send me file of this
    my email- suzi570451@gmail.com
    Thank you so much.

    ReplyDelete
  114. Dear
    I would like to see on the index page only the users where I chat how to do this by adding which php/script. so the user doesn't see all users.

    yours sincerely,

    klantenservice@leukekoopjes-gekkekoopjes.be

    ReplyDelete
  115. Hi Sir, I wanted to know , if i want to add a radio button and insert the value in the database, what should i do?

    ReplyDelete
  116. when the message is sent the latest message is upper and last message is bottom how to convert like the mesenger is

    ReplyDelete
  117. after message is sent the latest message is uper and the previous message is the bottom i need to converse it. who can help me please

    ReplyDelete
  118. after message is sent the latest message is upper and the first one is bottom. i ineed to converse it. who can help me please

    ReplyDelete
  119. Online ofline user didn't work plese help

    ReplyDelete
  120. I tried to create the web chat ... chat function working fine .. but i am not getting the user status.. its always showing as offline .. Also the group chat not working ... please help

    ReplyDelete
  121. Thanks sir, pls sir I need the file of the project..... @Samsonoluwadamilare19@gmail.com

    ReplyDelete
  122. Hi, can u please send source code at aishanazeer04@gmail.com

    ReplyDelete
  123. Hi
    Can you share the sql code or show us how to do it detailed?

    ReplyDelete
  124. hi
    can you post the sql code

    ReplyDelete
  125. I love your code. the way you used functions to encapsulate logic. I have a question, do you have code for two factor authentication in php?

    ReplyDelete
  126. hello sir can u send the project file please !
    my email : seifbenmansourabc@gmail.com

    ReplyDelete
  127. Great Work Sir. little problems with emoji. its shows ? mark

    ReplyDelete
  128. can you uploaded it to GitHub ... and set a URL to go to download it.

    ReplyDelete
  129. Hi,

    Can you send me project file to this email emishperraj@gmail.com please?

    Thanks

    ReplyDelete
  130. Hiya
    Anychance you can send me the code via my email plz

    ReplyDelete
  131. Great job! Please send me project file to my email - peter.a.adegboyega@gmail.com

    Many thanks sir

    ReplyDelete