Sunday, 29 March 2020

Ajax jQuery Real Time Chat Application using Codeigniter



Are you looking for tutorial on How to Create Real Time Chat Application in Codeigniter using Ajax jQuery. So, you have come on the right place because in this post you can find and learn How to implement a chat application in Codeigniter website using Ajax, jQuery, Mysql Database and json. By using this tutorial, every one can build their own chat app in Codeigniter framework, and this app will be real time because here we have use Ajax jQuery and json so all data will refresh without refresh of web page. So, here you can make your live chat application with Codeigniter framework. One more benefits of this tutorial is that you can make Facebook like chat application in Codeigniter.

If you are PHP developers, then every PHP developer is first prefer Codeigniter framework, this is because Codeigniter framework is fast application development framework, this framework has provide in build library, helper function using PHP which will helps to you to speed up build web based application. If you have use Codeigniter framework, then you can developed web application faster than you have start coding web application from scratch. So, you want to build your own chat application, you have to prefer any PHP framework like Codeigniter. This is because it is pur MVC framework, which will build light chat application.




In this post we will use Codeigniter framework for build Real time web based text messaging application, that means one person can send text message to another person on internet in real time. You chat build chat application like Facebook. One person can make live conversation with multiple person. Real time or live chat means online conversation in which sender or receiver will send and receiver text messages. In this chat application will make feature like one person can chat with one person or one person can chat with multiple person also. There are many Chat application available on internet, but if you want to build you own chat application, then you have to first select technology in which you want to build you chat application. Here we have use Codeigniter and Mysql database as server side technology, and at jQuery, Ajax, JSON has been used at client technology. Below you can find basic feature of this chat application.

  • Chat Application with Google Account Login
  • Search New User for Chat
  • Send Chat Request to New User
  • Load Chat Request Notification
  • Receiver User Accept Chat Request
  • Load Chat Request Accepted User
  • Send Chat Messages
  • Load Chat Messages
  • Display Unread Messsage Notification
  • Chat User Online or Offline Status
  • Display User is Typing




Datase Structure


If you want to make Chat application in Codeigniter framework, then first you have to make Mysql Database. Once you have make database, then For this you have to run following SQL script, it will make required tables in you database.


--
-- Database: `codeigniter_chat`
--

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

--
-- Table structure for table `chat_messages`
--

CREATE TABLE `chat_messages` (
  `chat_messages_id` int(11) NOT NULL,
  `sender_id` int(11) NOT NULL,
  `receiver_id` int(11) NOT NULL,
  `chat_messages_text` text NOT NULL,
  `chat_messages_status` enum('no','yes') NOT NULL,
  `chat_messages_datetime` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

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

--
-- Table structure for table `chat_request`
--

CREATE TABLE `chat_request` (
  `chat_request_id` int(11) NOT NULL,
  `sender_id` int(11) NOT NULL,
  `receiver_id` int(11) NOT NULL,
  `chat_request_status` enum('Accept','Reject') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

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

--
-- Table structure for table `chat_user`
--

CREATE TABLE `chat_user` (
  `user_id` int(11) NOT NULL,
  `login_oauth_uid` varchar(100) NOT NULL,
  `first_name` varchar(250) NOT NULL,
  `last_name` varchar(250) NOT NULL,
  `email_address` varchar(250) NOT NULL,
  `profile_picture` varchar(250) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Table structure for table `login_data`
--

CREATE TABLE `login_data` (
  `login_data_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `last_activity` datetime NOT NULL,
  `is_type` enum('no', 'yes') NOT NULL
  `receiver_user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `chat_messages`
--
ALTER TABLE `chat_messages`
  ADD PRIMARY KEY (`chat_messages_id`);

--
-- Indexes for table `chat_request`
--
ALTER TABLE `chat_request`
  ADD PRIMARY KEY (`chat_request_id`);

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

--
-- Indexes for table `login_data`
--
ALTER TABLE `login_data`
  ADD PRIMARY KEY (`login_data_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `chat_messages`
--
ALTER TABLE `chat_messages`
  MODIFY `chat_messages_id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `chat_request`
--
ALTER TABLE `chat_request`
  MODIFY `chat_request_id` int(11) NOT NULL AUTO_INCREMENT;

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

--
-- AUTO_INCREMENT for table `login_data`
--
ALTER TABLE `login_data`
  MODIFY `login_data_id` int(11) NOT NULL AUTO_INCREMENT;





Google Account Login Integration


In this chat application, we have use Google Account for login into system. This is because currently, most of the person have Google account, so then can directly login into system without register into this chat application.


In Codeigniter framework, First we have to define autoload libraries. So, every time define Codeigniter library we do want to define every time. For this, we have to open config/autoload.php file and define autoload libraries.



$autoload['libraries'] = array('database','session');


After define library, we can also define which helper we want to load at the time of initialize application. For this also we have to open config/autoload.php file.



$autoload['helper'] = array('url', 'form');


Now we want to define base url of Codeigniter chat application, for this we have open config/config.php file and define base url of this Codeigniter chat application.



$config['base_url'] = 'http://localhost/tutorial/codeigniter/';


After this we want to make database connection. So for database connection in Codeigniter framework, we have to open config/database.php file and in this file we have to define Mysql database configuration.



$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'codeigniter_chat',
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);


For integrate Google Account login into this Codeigniter Chat system, we have make following file Model Views and Controller files.


Controllers

In Controller folder we have make two file like Google_login.php and Chat.php file. In Google_login.php file, we have make following method.


__construct() - This is magic method and this method block of code will execute when new object of this class has been created and it will load Google_login_model.php all method.

index() - This is root method of this controller, and it will load login function.

login() - This method is communicate with Google API for validate User Google Account credential. If Google Account login detail is propert then it will redirect to this chat application url, which we have define at then time creating Google API key. After this User detail will store in database, and for validate User login here we have store user_id data has been store in session variable and at the time of login into system login date and time data has been store in database also. If Google login is proper then it will redirect to Chat application home page.

logout() - This method will logout user from this chat application, and redirect page to login page.


controllers/Google_login.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Google_login extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('google_login_model');
 }

 function index()
 {
  $this->login();
 }

 function login()
 {
  include_once APPPATH . "libraries/vendor/autoload.php";

  $google_client = new Google_Client();

  $google_client->setClientId('');

  $google_client->setClientSecret('');

  $google_client->setRedirectUri('');

  $google_client->addScope('email');

  $google_client->addScope('profile');

  if(isset($_GET["code"]))
  {
   $token = $google_client->fetchAccessTokenWithAuthCode($_GET["code"]);

   if(!isset($token["error"]))
   {
    $google_client->setAccessToken($token['access_token']);

    $this->session->set_userdata('access_token', $token['access_token']);

    $google_service = new Google_Service_Oauth2($google_client);

    $data = $google_service->userinfo->get();

    $current_datetime = date('Y-m-d H:i:s');

    if($this->google_login_model->Is_already_register($data['id']))
    {
     //update data
     $user_data = array(
      'login_oauth_uid' => $data['id'],
      'first_name'  => $data['given_name'],
      'last_name'   => $data['family_name'],
      'email_address'  => $data['email'],
      'profile_picture' => $data['picture'],
      'updated_at'  => $current_datetime
     );

     $this->google_login_model->Update_user_data($user_data, $data['id']);
    }
    else
    {
     //insert data
     $user_data = array(
      'login_oauth_uid' => $data['id'],
      'first_name'  => $data['given_name'],
      'last_name'   => $data['family_name'],
      'email_address'  => $data['email'],
      'profile_picture' => $data['picture'],
      'created_at'  => $current_datetime
     );

     $this->google_login_model->Insert_user_data($user_data);
    }
    
    //$this->session->set_userdata('user_data', $user_data);

    $user_id = $this->google_login_model->Get_user_id($data['id']);

    $login_data = array(
     'user_id'  => $user_id,
     'last_activity' => $current_datetime
    );

    $login_id = $this->google_login_model->Insert_login_data($login_data);

    $this->session->set_userdata('username', ucfirst($data['given_name']) . ' ' . ucfirst($data['family_name']));

    $this->session->set_userdata('user_id', $user_id);

    $this->session->set_userdata('login_id', $login_id);
   }
  }
  $login_button = '';
  if(!$this->session->userdata('access_token'))
  {
   $login_button = '<a href="'.$google_client->createAuthUrl().'"><img src="'.base_url().'asset/sign-in-with-google.png" /></a>';
   $data['login_button'] = $login_button;
   $this->load->view('google_login', $data);
  }
  else
  {
   //$this->load->view('google_login');
   redirect('chat');
  }
 }

 function logout()
 {
  $this->session->unset_userdata('access_token');

  $this->session->unset_userdata('user_id');

  $this->session->unset_userdata('login_id');

  redirect('google_login/login');
 }
 
}
?>


Here we have make one another controller class, which is Chat.php file and in this we have make following method.


__construct() - This method will load Chat_model.php class method, and here it will also check user session data for check user is login into system or not, If User is not login into system, then it will redirect page to Login page.

index() - This is root method of this Chat class, and it will load chat_view.php view file for display html output in browser.


controllers/Chat.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Chat extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('chat_model');
  if(!$this->session->userdata('user_id'))
  {
   redirect('google_login/login');
  }
 }

 function index()
 {
  $this->load->view('chat_view');
 }
}
?>


Models


For integrate Google Account login into chat system, we have to make Google_login_model.php models class and in this class we have make following method.


Is_already_register($id) - This will check particular user is already register in our system or not.

Update_user_data($data, $id) - This method will update existing user data in Mysql database.

Insert_user_data($data) - This method will insert new User data in Mysql database.

Get_user_id($id) - This method will return login user id based on open source authentic login id which has been provided by Google.

Insert_login_data($data) - This method will insert user login date and time data into mysql database.


models/Google_login_model.php

<?php
class Google_login_model extends CI_Model
{
 function Is_already_register($id)
 {
  $this->db->where('login_oauth_uid', $id);
  $query = $this->db->get('chat_user');
  if($query->num_rows() > 0)
  {
   return true;
  }
  else
  {
   return false;
  }
 }

 function Update_user_data($data, $id)
 {
  $this->db->where('login_oauth_uid', $id);
  $this->db->update('chat_user', $data);
 }

 function Insert_user_data($data)
 {
  $this->db->insert('chat_user', $data);
 }

 function Get_user_id($id)
 {
  $this->db->select('user_id');
  $this->db->from('chat_user');
  $this->db->where('login_oauth_uid', $id);
  $query = $this->db->get();
  foreach($query->result() as $row)
  {
   return $row->user_id;
  }
 }

 function Insert_login_data($data)
 {
  $this->db->insert('login_data', $data);
  return $this->db->insert_id();
 }
}
?>


Views


For integrate Google Account login, here we have we have make two views file like google_login.php and chat_view.php file.


views/google_login.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Chat Application in Codeigniter</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

  <style>
      /* Remove the navbar's default margin-bottom and rounded borders */ 
      .navbar {
        margin-bottom: 0;
        border-radius: 0;
      }
      
      /* Set height of the grid so .sidenav can be 100% (adjust as needed) */
      .row.content {height: 450px}
      
      /* Set gray background color and 100% height */
      .sidenav {
        padding-top: 20px;
        background-color: #f1f1f1;
        height: 100%;
      }
      
      /* Set black background color, white text and some padding */
      footer {
        background-color: #555;
        color: white;
        padding: 15px;
      }
      
      /* On small screens, set height to 'auto' for sidenav and grid */
      @media screen and (max-width: 767px) {
        .sidenav {
          height: auto;
          padding: 15px;
        }
        .row.content {height:auto;} 
      }
    </style>
  
 </head>
 <body>
  <div class="container">
   <br />
   <h2 align="center"><a href="#">Chat Application in Codeigniter</a></h2>
                        <br />
   <div class="panel panel-default">
   <?php
   if(!isset($login_button))
   {
    redirect('chat');
   }
   else
   {
    echo '<div align="center">'.$login_button . '</div>';
   }
   ?>
   <br />
   <br />
   </div>
  </div>

 </body>
</html>


views/chat_view.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Chat Application in Codeigniter</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="<?php echo base_url(); ?>asset/js/jquery.min.js"></script>
  <script src="<?php echo base_url(); ?>asset/js/bootstrap.min.js"></script>
  <link href="<?php echo base_url(); ?>asset/css/bootstrap.min.css" rel="stylesheet" />
  <style type="text/css">
   
   #chat_message_area
   {
    width: 100%;
    height: auto;
    min-height: 80px;
    overflow: auto;
    padding:6px 24px 6px 12px;
    border: 1px solid #CCC;
       border-radius: 3px;
   }

   .notification_circle {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #FF0000;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .online
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #5cb85c;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .offline
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #ccc;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }

  </style>
 </head>
 <body>
  <div clas="container-fluid">
   <br />
   <h2 align="center">Chat Application in Codeigniter</h2>
   <br />
   <div class="col-md-12" align="right">
    <a href="<?php echo base_url(); ?>google_login/logout">Logout</a>
   </div>
   <div class="col-md-3" style="padding-right:0;">
    <div class="panel panel-default" style="height: 700px; overflow-y: scroll;">
     <div class="panel-heading">Chat with User</div>
     <div class="panel-body" id="chat_user_area">

     </div>
     <input type="hidden" name="hidden_receiver_id_array" id="hidden_receiver_id_array" />
    </div>
   </div>
   <div class="col-md-6" style="padding-left:0; padding-right: 0;">
    <div class="panel panel-default" style="">
     <div class="panel-heading">Chat Area</div>
     <div class="panel-body">
      <div id="chat_header">
       <h2 align="center" style="margin:0; padding-bottom:16px;"><span id="dynamic_title">Welcome <?php echo $this->session->userdata('username'); ?></span></h2>
      </div>
      <div id="chat_body" style="height:406px; overflow-y: scroll;"></div>
      <div id="chat_footer" style="">
       <hr />
       <div class="form-group">
        
       </div>
       <div class="form-group" align="right">
        
       </div>
      </div>
     </div>
    </div>
   </div>
   <div class="col-md-3" style="padding-left:0;">
    <div class="panel panel-default" style="height: 300px; overflow-y: scroll;">
     <div class="panel-heading">Search User</div>
     <div class="panel-body">
      <div class="row">
       <div class="col-md-8">
        
       </div>
       <div class="col-md-4">
        
       </div>
      </div>
      
      <div id="search_user_area"></div>
      
     </div>
    </div>
    <div class="panel panel-default" style="height: 380px; overflow-y: scroll;">
     <div class="panel-heading">Nofication</div>
     <div class="panel-body" id="notification_area">
      
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script>

$(document).ready(function(){

 

});

</script>





Search New User for Chat


In this Chat application, for chat there is required some other person for chat. For this, here we have add chat user feature. By using this functionality, login user can search other person in this chat application.


Chat.php -


In this controller class, we have make forllowig method for make search feature in this Codeigniter chat application.


search_user() - This method will received Ajax request for search user data. This method has received data from model class method, and converted and store data in array formar and send back to Ajax request in json format.



<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Chat extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('chat_model');
  if(!$this->session->userdata('user_id'))
  {
   redirect('google_login/login');
  }
 }

 function index()
 {
  $this->load->view('chat_view');
 }

 function search_user()
 {
  sleep(2);
  if($this->input->post('search_query'))
  {
   $data = $this->chat_model->search_user_data($this->session->userdata('user_id'), $this->input->post('search_query'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $request_status = $this->chat_model->Check_request_status($this->session->userdata('user_id'), $row->user_id);
     $is_request_send = 'yes';
     if($request_status == '')
     {
      $is_request_send = 'no';
     } 
     else
     {
      if($request_status == 'pending')
      {
       $is_request_send = 'yes';
      }
     }
     if($request_status != 'Accept')
     {
      $output[] = array(
       'user_id'  => $row->user_id,
       'first_name' => $row->first_name,
       'last_name'  => $row->last_name,
       'profile_picture'=> $row->profile_picture,
       'is_request_send'=> $is_request_send
      );
     } 
    }
   }
   echo json_encode($output);
  }
 }
}

?>


Chat_model.php


In this model class, we have make following method for make search user functionality in this Chat application.


search_user_data($user_id, $query) - This method is used for fetch data from chat_user table. This method will not search user own data.


Check_request_status($sender_id, $receiver_id) - This method will check chat request status data in Mysql table.



<?php
class Chat_model extends CI_Model
{
 function search_user_data($user_id, $query)
 {
  $where = "user_id != '".$user_id."' AND (first_name LIKE '%".$query."%' OR last_name LIKE '%".$query."%')";

  $this->db->where($where);

  return $this->db->get('chat_user');
 }

 function Check_request_status($sender_id, $receiver_id)
 {
  $this->db->where('(sender_id = "'.$sender_id.'" OR sender_id = "'.$receiver_id.'")');
  $this->db->where('(receiver_id = "'.$receiver_id.'" OR receiver_id = "'.$sender_id.'")');
  $this->db->order_by('chat_request_id', 'DESC');
  $this->db->limit(1);
  $query = $this->db->get('chat_request');
  if($query->num_rows() > 0)
  {
   foreach($query->result() as $row)
   {
    return $row->chat_request_status;
   }
  }
 }
}
?>


chat_view.php


In this view file, first we have define on textbox for enter user name for search user and one button, after click on button, ajax request will triggered and it will send search user request send to server, and it will received data from server in json format and convert that data into html format and display in user search result on web page, without refresh for web page.



<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Chat Application in Codeigniter</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="<?php echo base_url(); ?>asset/js/jquery.min.js"></script>
  <script src="<?php echo base_url(); ?>asset/js/bootstrap.min.js"></script>
  <link href="<?php echo base_url(); ?>asset/css/bootstrap.min.css" rel="stylesheet" />
  <style type="text/css">
   
   #chat_message_area
   {
    width: 100%;
    height: auto;
    min-height: 80px;
    overflow: auto;
    padding:6px 24px 6px 12px;
    border: 1px solid #CCC;
       border-radius: 3px;
   }

   .notification_circle {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #FF0000;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .online
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #5cb85c;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .offline
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #ccc;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }

  </style>
 </head>
 <body>
  <div clas="container-fluid">
   <br />
   <h2 align="center">Chat Application in Codeigniter</h2>
   <br />
   <div class="col-md-12" align="right">
    <a href="<?php echo base_url(); ?>google_login/logout">Logout</a>
   </div>
   <div class="col-md-3" style="padding-right:0;">
    <div class="panel panel-default" style="height: 700px; overflow-y: scroll;">
     <div class="panel-heading">Chat with User</div>
     <div class="panel-body">

     </div>
    </div>
   </div>
   <div class="col-md-6" style="padding-left:0; padding-right: 0;">
    <div class="panel panel-default" style="">
     <div class="panel-heading">Chat Area</div>
     <div class="panel-body">
      <div id="chat_header">
       <h2 align="center" style="margin:0; padding-bottom:16px;"><span id="dynamic_title">Welcome <?php echo $this->session->userdata('username'); ?></span></h2>
      </div>
      <div id="chat_body" style="height:406px; overflow-y: scroll;"></div>
      
      </div>
     </div>
    </div>
   </div>
   <div class="col-md-3" style="padding-left:0;">
    <div class="panel panel-default" style="height: 300px; overflow-y: scroll;">
     <div class="panel-heading">Search User</div>
     <div class="panel-body">
      <div class="row">
       <div class="col-md-8">
        <input type="text" name="search_user" id="search_user" class="form-control input-sm" placeholder="Search User" />
       </div>
       <div class="col-md-4">
        <button type="button" name="search_button" id="search_button" class="btn btn-primary btn-sm">Search</button>
       </div>
      </div>
      
      <div id="search_user_area"></div>
      
     </div>
    </div>
    <div class="panel panel-default" style="height: 380px; overflow-y: scroll;">
     <div class="panel-heading">Nofication</div>
     <div class="panel-body">
      
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script>

$(document).ready(function(){

 function loading()
 {
  var output = '<div align="center"><br /><br /><br />';
  output += '<img src="<?php echo base_url(); ?>asset/loading.gif" /> Please wait...</div>';
  return output;
 }

 $(document).on('click', '#search_button', function(){
  var search_query = $.trim($('#search_user').val());
  $('#search_user_area').html('');
  if(search_query != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>chat/search_user",
    method:"POST",
    data:{search_query:search_query},
    dataType:"json",
    beforeSend:function()
    {
     $('#search_user_area').html(loading());
     $('#search_button').attr('disabled', 'disabled');
    },
    success:function(data)
    {
     $('#search_button').attr('disabled', false);
     var output = '<hr />';
     var send_userid = "<?php echo $this->session->userdata('user_id'); ?>";
     if(data.length > 0)
     {
      for(var count = 0; count < data.length; count++)
      {
       output += '<div class="row">';
       output += '<div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-thumbnail img-rounded" width="35" /> '+data[count].first_name+' '+data[count].last_name+'</div>';
       if(data[count].is_request_send == 'yes')
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-warning btn-xs">Request Sended</button></div>';
       }
       else
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-success btn-xs request_button" id="request_button'+data[count].user_id+'" data-receiver_userid="'+data[count].user_id+'" data-send_userid="'+send_userid+'">Send Request</button></div>';
       }
       output += '</div><hr />';
      }
     }
     else
     {
      output += '<div align="center"><b>No Data Found</b></div>';
     }
     output += '</div>';
     $('#search_user_area').html(output);
    }
   })
  }
 });
});

</script>





Send Chat Request to New User


If you have start search new user in this Chat application, then in search result you can see user profile picture, user name and send request button. By click on send request button, user can send chat request to another user from search result. For this feature we have make following changes in Codeigniter Controllers, Models and views file.


Chat.php (Controllers)


For make send chat request functionality, in Codeigniter controller class, we have make following method.

send_request() - This method will received ajax request for send chat request to another user. It will send data to models class method for store chat request data into Mysql database.



<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Chat extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('chat_model');
  if(!$this->session->userdata('user_id'))
  {
   redirect('google_login/login');
  }
 }

 function index()
 {
  $this->load->view('chat_view');
 }

 function search_user()
 {
  sleep(2);
  if($this->input->post('search_query'))
  {
   $data = $this->chat_model->search_user_data($this->session->userdata('user_id'), $this->input->post('search_query'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $request_status = $this->chat_model->Check_request_status($this->session->userdata('user_id'), $row->user_id);
     $is_request_send = 'yes';
     if($request_status == '')
     {
      $is_request_send = 'no';
     } 
     else
     {
      if($request_status == 'pending')
      {
       $is_request_send = 'yes';
      }
     }
     if($request_status != 'Accept')
     {
      $output[] = array(
       'user_id'  => $row->user_id,
       'first_name' => $row->first_name,
       'last_name'  => $row->last_name,
       'profile_picture'=> $row->profile_picture,
       'is_request_send'=> $is_request_send
      );
     } 
    }
   }
   echo json_encode($output);
  }
 }

 function send_request()
 {
  sleep(2);
  if($this->input->post('send_userid'))
  {
   $data = array(
    'sender_id'  => $this->input->post('send_userid'),
    'receiver_id' => $this->input->post('receiver_userid')
   );
   $this->chat_model->Insert_chat_request($data);
  }
 }
}

?>


Chat_model.php (Models)


This models class will handle database related operation for make send chat request feature in Codeigniter chat application. In this class we have make following method.

Insert_chat_request($data) - This method will insert chat request data in Mysql data. It will received data fron Controller class method.



<?php
class Chat_model extends CI_Model
{
 function search_user_data($user_id, $query)
 {
  $where = "user_id != '".$user_id."' AND (first_name LIKE '%".$query."%' OR last_name LIKE '%".$query."%')";

  $this->db->where($where);

  return $this->db->get('chat_user');
 }

 function Check_request_status($sender_id, $receiver_id)
 {
  $this->db->where('(sender_id = "'.$sender_id.'" OR sender_id = "'.$receiver_id.'")');
  $this->db->where('(receiver_id = "'.$receiver_id.'" OR receiver_id = "'.$sender_id.'")');
  $this->db->order_by('chat_request_id', 'DESC');
  $this->db->limit(1);
  $query = $this->db->get('chat_request');
  if($query->num_rows() > 0)
  {
   foreach($query->result() as $row)
   {
    return $row->chat_request_status;
   }
  }
 }

 function Insert_chat_request($data)
 {
  $this->db->insert('chat_request', $data);
 }
}
?>


chat_view.php (Views)


This view file will use Ajax request for send chat request to another user. For make Send request feature for Chat Application in this View file we have use Ajax request. By click on request button, this system will send chat request data to another user using Ajax request.



<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Chat Application in Codeigniter</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="<?php echo base_url(); ?>asset/js/jquery.min.js"></script>
  <script src="<?php echo base_url(); ?>asset/js/bootstrap.min.js"></script>
  <link href="<?php echo base_url(); ?>asset/css/bootstrap.min.css" rel="stylesheet" />
  <style type="text/css">
   
   #chat_message_area
   {
    width: 100%;
    height: auto;
    min-height: 80px;
    overflow: auto;
    padding:6px 24px 6px 12px;
    border: 1px solid #CCC;
       border-radius: 3px;
   }

   .notification_circle {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #FF0000;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .online
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #5cb85c;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .offline
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #ccc;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }

  </style>
 </head>
 <body>
  <div clas="container-fluid">
   <br />
   <h2 align="center">Chat Application in Codeigniter</h2>
   <br />
   <div class="col-md-12" align="right">
    <a href="<?php echo base_url(); ?>google_login/logout">Logout</a>
   </div>
   <div class="col-md-3" style="padding-right:0;">
    <div class="panel panel-default" style="height: 700px; overflow-y: scroll;">
     <div class="panel-heading">Chat with User</div>
     <div class="panel-body">

     </div>
     <input type="hidden" name="hidden_receiver_id_array" id="hidden_receiver_id_array" />
    </div>
   </div>
   <div class="col-md-6" style="padding-left:0; padding-right: 0;">
    <div class="panel panel-default" style="">
     <div class="panel-heading">Chat Area</div>
     <div class="panel-body">
      <div id="chat_header">
       <h2 align="center" style="margin:0; padding-bottom:16px;"><span id="dynamic_title">Welcome <?php echo $this->session->userdata('username'); ?></span></h2>
      </div>
      <div id="chat_body" style="height:406px; overflow-y: scroll;"></div>
      <div id="chat_footer" style="">
       <hr />
       <div class="form-group">
        
       </div>
       <div class="form-group" align="right">
        
       </div>
      </div>
     </div>
    </div>
   </div>
   <div class="col-md-3" style="padding-left:0;">
    <div class="panel panel-default" style="height: 300px; overflow-y: scroll;">
     <div class="panel-heading">Search User</div>
     <div class="panel-body">
      <div class="row">
       <div class="col-md-8">
        <input type="text" name="search_user" id="search_user" class="form-control input-sm" placeholder="Search User" />
       </div>
       <div class="col-md-4">
        <button type="button" name="search_button" id="search_button" class="btn btn-primary btn-sm">Search</button>
       </div>
      </div>
      
      <div id="search_user_area"></div>
      
     </div>
    </div>
    <div class="panel panel-default" style="height: 380px; overflow-y: scroll;">
     <div class="panel-heading">Nofication</div>
     <div class="panel-body">
      
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script>

$(document).ready(function(){

 function loading()
 {
  var output = '<div align="center"><br /><br /><br />';
  output += '<img src="<?php echo base_url(); ?>asset/loading.gif" /> Please wait...</div>';
  return output;
 }

 $(document).on('click', '#search_button', function(){
  var search_query = $.trim($('#search_user').val());
  $('#search_user_area').html('');
  if(search_query != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>chat/search_user",
    method:"POST",
    data:{search_query:search_query},
    dataType:"json",
    beforeSend:function()
    {
     $('#search_user_area').html(loading());
     $('#search_button').attr('disabled', 'disabled');
    },
    success:function(data)
    {
     $('#search_button').attr('disabled', false);
     var output = '<hr />';
     var send_userid = "<?php echo $this->session->userdata('user_id'); ?>";
     if(data.length > 0)
     {
      for(var count = 0; count < data.length; count++)
      {
       output += '<div class="row">';
       output += '<div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="40" /> <small>'+data[count].first_name+' '+data[count].last_name+'</small></div>';
       if(data[count].is_request_send == 'yes')
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-warning btn-xs">Request Sended</button></div>';
       }
       else
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-success btn-xs request_button" id="request_button'+data[count].user_id+'" data-receiver_userid="'+data[count].user_id+'" data-send_userid="'+send_userid+'">Send Request</button></div>';
       }
       output += '</div><hr />';
      }
     }
     else
     {
      output += '<div align="center"><b>No Data Found</b></div>';
     }
     output += '</div>';
     $('#search_user_area').html(output);
    }
   })
  }
 });

 $(document).on('click', '.request_button', function(){
  var id = $(this).attr('id');
  var receiver_userid = $(this).data('receiver_userid');
  var send_userid = $(this).data('send_userid');
  $.ajax({
   url:"<?php echo base_url(); ?>chat/send_request",
   method:"POST",
   data:{receiver_userid:receiver_userid, send_userid:send_userid},
   beforeSend:function()
   {
    $('#'+id).attr('disabled', 'disabled');
   },
   success:function(data)
   {
    $('#'+id).attr('disabled', false);
    $('#'+id).removeClass('btn-success');
    $('#'+id).addClass('btn-warning');
    $('#'+id).text('Request Sended');
   }
  })
 });
});
</script>


Load Chat Request Notification


Once User has send chat request, then at receiver user side they will seen notification of chat request has been received at their chat system page. For this feature we have to make following method in Controller and models class.


Chat.php (Controllers)


In controller class, for load chat notification data at receiver user area, we have create following method in controller class.

load_notification() - This method will received ajax request for load notification data in notification area. This method will get data from Fetch_notification_data() model method, and convert that data into array for and send to ajax request in json format.



<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Chat extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('chat_model');
  if(!$this->session->userdata('user_id'))
  {
   redirect('google_login/login');
  }
 }

 function index()
 {
  $this->load->view('chat_view');
 }

 function search_user()
 {
  sleep(2);
  if($this->input->post('search_query'))
  {
   $data = $this->chat_model->search_user_data($this->session->userdata('user_id'), $this->input->post('search_query'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $request_status = $this->chat_model->Check_request_status($this->session->userdata('user_id'), $row->user_id);
     $is_request_send = 'yes';
     if($request_status == '')
     {
      $is_request_send = 'no';
     } 
     else
     {
      if($request_status == 'pending')
      {
       $is_request_send = 'yes';
      }
     }
     if($request_status != 'Accept')
     {
      $output[] = array(
       'user_id'  => $row->user_id,
       'first_name' => $row->first_name,
       'last_name'  => $row->last_name,
       'profile_picture'=> $row->profile_picture,
       'is_request_send'=> $is_request_send
      );
     } 
    }
   }
   echo json_encode($output);
  }
 }

 function send_request()
 {
  sleep(2);
  if($this->input->post('send_userid'))
  {
   $data = array(
    'sender_id'  => $this->input->post('send_userid'),
    'receiver_id' => $this->input->post('receiver_userid')
   );
   $this->chat_model->Insert_chat_request($data);
  }
 }

 function load_notification()
 {
  sleep(2);
  if($this->input->post('action'))
  {
   $data = $this->chat_model->Fetch_notification_data($this->session->userdata('user_id'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $userdata = $this->chat_model->Get_user_data($row->sender_id);

     $output[] = array(
      'user_id'  => $row->sender_id,
      'first_name' => $userdata['first_name'],
      'last_name'  => $userdata['last_name'],
      'profile_picture' => $userdata['profile_picture'],
      'chat_request_id' => $row->chat_request_id
     );
    }
   }
   echo json_encode($output);
  }
 }
}
?>


Chat_model.php (Models)


For load notification data in this chat application, In this models, we have make following method for Mysql database related operation.


Fetch_notification_data($receiver_id) - This method has been fetch notification data from Mysql database.

Get_user_data($user_id) - This method will fetch particular user data from Mysql database.



<?php
class Chat_model extends CI_Model
{
 function search_user_data($user_id, $query)
 {
  $where = "user_id != '".$user_id."' AND (first_name LIKE '%".$query."%' OR last_name LIKE '%".$query."%')";

  $this->db->where($where);

  return $this->db->get('chat_user');
 }

 function Check_request_status($sender_id, $receiver_id)
 {
  $this->db->where('(sender_id = "'.$sender_id.'" OR sender_id = "'.$receiver_id.'")');
  $this->db->where('(receiver_id = "'.$receiver_id.'" OR receiver_id = "'.$sender_id.'")');
  $this->db->order_by('chat_request_id', 'DESC');
  $this->db->limit(1);
  $query = $this->db->get('chat_request');
  if($query->num_rows() > 0)
  {
   foreach($query->result() as $row)
   {
    return $row->chat_request_status;
   }
  }
 }

 function Insert_chat_request($data)
 {
  $this->db->insert('chat_request', $data);
 }

 function Fetch_notification_data($receiver_id)
 {
  $this->db->where('receiver_id', $receiver_id);
  $this->db->where('chat_request_status', 'Pending');
  return $this->db->get('chat_request');
 }

 function Get_user_data($user_id)
 {
  $this->db->where('user_id', $user_id);
  $data = $this->db->get('chat_user');
  $output = array();
  foreach($data->result() as $row)
  {
   $output['first_name'] = $row->first_name;
   $output['last_name'] = $row->last_name;
   $output['email_address'] = $row->email_address;
   $output['profile_picture'] = $row->profile_picture;
  }
  return $output;
 }
}
?>


chat_view.php (Views)


In this view file, for load chat request notification data. First we have define division tag for display notification data and then after by using Ajax request. It will load chat request notification data. In Ajax it has been received data in JSON format and then after convert into HTML format and display on web page.



<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Chat Application in Codeigniter</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="<?php echo base_url(); ?>asset/js/jquery.min.js"></script>
  <script src="<?php echo base_url(); ?>asset/js/bootstrap.min.js"></script>
  <link href="<?php echo base_url(); ?>asset/css/bootstrap.min.css" rel="stylesheet" />
  <style type="text/css">
   
   #chat_message_area
   {
    width: 100%;
    height: auto;
    min-height: 80px;
    overflow: auto;
    padding:6px 24px 6px 12px;
    border: 1px solid #CCC;
       border-radius: 3px;
   }

   .notification_circle {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #FF0000;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .online
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #5cb85c;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .offline
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #ccc;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }

  </style>
 </head>
 <body>
  <div clas="container-fluid">
   <br />
   <h2 align="center"><a href="https://www.webslesson.info/2020/03/ajax-jquery-real-time-chat-application-using-codeigniter.html">Chat Application in Codeigniter</a></h2>
   <br />
   <div class="col-md-12" align="right">
    <a href="<?php echo base_url(); ?>google_login/logout">Logout</a>
   </div>
   <div class="col-md-3" style="padding-right:0;">
    <div class="panel panel-default" style="height: 700px; overflow-y: scroll;">
     <div class="panel-heading">Chat with User</div>
     <div class="panel-body" id="chat_user_area">

     </div>
     
    </div>
   </div>
   <div class="col-md-6" style="padding-left:0; padding-right: 0;">
    <div class="panel panel-default" style="">
     <div class="panel-heading">Chat Area</div>
     <div class="panel-body">
      <div id="chat_header">
       <h2 align="center" style="margin:0; padding-bottom:16px;"><span id="dynamic_title">Welcome <?php echo $this->session->userdata('username'); ?></span></h2>
      </div>
      <div id="chat_body" style="height:406px; overflow-y: scroll;"></div>
      <div id="chat_footer" style="">
       <hr />
       <div class="form-group">
        
       </div>
       <div class="form-group" align="right">
        
       </div>
      </div>
     </div>
    </div>
   </div>
   <div class="col-md-3" style="padding-left:0;">
    <div class="panel panel-default" style="height: 300px; overflow-y: scroll;">
     <div class="panel-heading">Search User</div>
     <div class="panel-body">
      <div class="row">
       <div class="col-md-8">
        <input type="text" name="search_user" id="search_user" class="form-control input-sm" placeholder="Search User" />
       </div>
       <div class="col-md-4">
        <button type="button" name="search_button" id="search_button" class="btn btn-primary btn-sm">Search</button>
       </div>
      </div>
      
      <div id="search_user_area"></div>
      
     </div>
    </div>
    <div class="panel panel-default" style="height: 380px; overflow-y: scroll;">
     <div class="panel-heading">Nofication</div>
     <div class="panel-body" id="notification_area">
      
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script>

$(document).ready(function(){

 function loading()
 {
  var output = '<div align="center"><br /><br /><br />';
  output += '<img src="<?php echo base_url(); ?>asset/loading.gif" /> Please wait...</div>';
  return output;
 }

 $(document).on('click', '#search_button', function(){
  var search_query = $.trim($('#search_user').val());
  $('#search_user_area').html('');
  if(search_query != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>chat/search_user",
    method:"POST",
    data:{search_query:search_query},
    dataType:"json",
    beforeSend:function()
    {
     $('#search_user_area').html(loading());
     $('#search_button').attr('disabled', 'disabled');
    },
    success:function(data)
    {
     $('#search_button').attr('disabled', false);
     var output = '<hr />';
     var send_userid = "<?php echo $this->session->userdata('user_id'); ?>";
     if(data.length > 0)
     {
      for(var count = 0; count < data.length; count++)
      {
       output += '<div class="row">';
       output += '<div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="40" /> <small>'+data[count].first_name+' '+data[count].last_name+'</small></div>';
       if(data[count].is_request_send == 'yes')
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-warning btn-xs">Request Sended</button></div>';
       }
       else
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-success btn-xs request_button" id="request_button'+data[count].user_id+'" data-receiver_userid="'+data[count].user_id+'" data-send_userid="'+send_userid+'">Send Request</button></div>';
       }
       output += '</div><hr />';
      }
     }
     else
     {
      output += '<div align="center"><b>No Data Found</b></div>';
     }
     output += '</div>';
     $('#search_user_area').html(output);
    }
   })
  }
 });

 $(document).on('click', '.request_button', function(){
  var id = $(this).attr('id');
  var receiver_userid = $(this).data('receiver_userid');
  var send_userid = $(this).data('send_userid');
  $.ajax({
   url:"<?php echo base_url(); ?>chat/send_request",
   method:"POST",
   data:{receiver_userid:receiver_userid, send_userid:send_userid},
   beforeSend:function()
   {
    $('#'+id).attr('disabled', 'disabled');
   },
   success:function(data)
   {
    $('#'+id).attr('disabled', false);
    $('#'+id).removeClass('btn-success');
    $('#'+id).addClass('btn-warning');
    $('#'+id).text('Request Sended');
   }
  })
 })

 load_notification();

 function load_notification()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_notification",
   method:"POST",
   data:{action:'load_notification'},
   dataType:"json",
   beforeSend:function()
   {
    $('#notification_area').html(loading());
   },
   success:function(data)
   {
    var output = '<hr />';
    //console.log(data.length);
    if(data.length > 0)
    {
     for(var count = 0; count < data.length; count++)
     {
      output += '<div class="row"><div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="35" /> ' + data[count].first_name + ' ' +data[count].last_name + '</div>';

      output += '<div class="col-md-5"><button type="button" name="accept_button" class="btn btn-success btn-xs accept_button" id="accept_button'+data[count].user_id+'" data-chat_request_id="'+data[count].chat_request_id+'">Accept</button></div><hr />';
     }
    }
    else
    {
     output += '<div align="center"><b>No Data Found</b></div>';
    }
    //output += '</div><hr />';
    $('#notification_area').html(output);
   }
  }) 
 }

});
</script>





Receiver User Accept Chat Request


After load chat request notification data at receiver user, so at that chat request notification data, receiver user can also see accept button for approve chat request. By click on Accept button receiver user can approve chat request and sender and receiver user can chat with each other. For accept chat request in this Codeigniter Chat syste, we have make following method in Controllers, Models class and views file.

Chat.php (Controllers)


In controllers class we have make following method for accept chat request feature in this chat application.

accept_request() - This method will received Ajax request for accept chat request. This method will send this request to model Update_chat_request() method.



<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Chat extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('chat_model');
  if(!$this->session->userdata('user_id'))
  {
   redirect('google_login/login');
  }
 }

 function index()
 {
  $this->load->view('chat_view');
 }

 function search_user()
 {
  sleep(2);
  if($this->input->post('search_query'))
  {
   $data = $this->chat_model->search_user_data($this->session->userdata('user_id'), $this->input->post('search_query'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $request_status = $this->chat_model->Check_request_status($this->session->userdata('user_id'), $row->user_id);
     $is_request_send = 'yes';
     if($request_status == '')
     {
      $is_request_send = 'no';
     } 
     else
     {
      if($request_status == 'pending')
      {
       $is_request_send = 'yes';
      }
     }
     if($request_status != 'Accept')
     {
      $output[] = array(
       'user_id'  => $row->user_id,
       'first_name' => $row->first_name,
       'last_name'  => $row->last_name,
       'profile_picture'=> $row->profile_picture,
       'is_request_send'=> $is_request_send
      );
     } 
    }
   }
   echo json_encode($output);
  }
 }

 function send_request()
 {
  sleep(2);
  if($this->input->post('send_userid'))
  {
   $data = array(
    'sender_id'  => $this->input->post('send_userid'),
    'receiver_id' => $this->input->post('receiver_userid')
   );
   $this->chat_model->Insert_chat_request($data);
  }
 }

 function load_notification()
 {
  sleep(2);
  if($this->input->post('action'))
  {
   $data = $this->chat_model->Fetch_notification_data($this->session->userdata('user_id'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $userdata = $this->chat_model->Get_user_data($row->sender_id);

     $output[] = array(
      'user_id'  => $row->sender_id,
      'first_name' => $userdata['first_name'],
      'last_name'  => $userdata['last_name'],
      'profile_picture' => $userdata['profile_picture'],
      'chat_request_id' => $row->chat_request_id
     );
    }
   }
   echo json_encode($output);
  }
 }

 function accept_request()
 {
  if($this->input->post('chat_request_id'))
  {
   $update_data = array(
    'chat_request_status' => 'Accept'
   );
   $this->chat_model->Update_chat_request($this->input->post('chat_request_id'), $update_data);
  }
 }
}
?>


Chat_model.php - (Models)


In this model class, we have to make following method for database related operation for accept chat request.

Update_chat_request($chat_request_id, $data) - This method will update chat request status in Mysql table.



<?php
class Chat_model extends CI_Model
{
 function search_user_data($user_id, $query)
 {
  $where = "user_id != '".$user_id."' AND (first_name LIKE '%".$query."%' OR last_name LIKE '%".$query."%')";

  $this->db->where($where);

  return $this->db->get('chat_user');
 }

 function Check_request_status($sender_id, $receiver_id)
 {
  $this->db->where('(sender_id = "'.$sender_id.'" OR sender_id = "'.$receiver_id.'")');
  $this->db->where('(receiver_id = "'.$receiver_id.'" OR receiver_id = "'.$sender_id.'")');
  $this->db->order_by('chat_request_id', 'DESC');
  $this->db->limit(1);
  $query = $this->db->get('chat_request');
  if($query->num_rows() > 0)
  {
   foreach($query->result() as $row)
   {
    return $row->chat_request_status;
   }
  }
 }

 function Insert_chat_request($data)
 {
  $this->db->insert('chat_request', $data);
 }

 function Fetch_notification_data($receiver_id)
 {
  $this->db->where('receiver_id', $receiver_id);
  $this->db->where('chat_request_status', 'Pending');
  return $this->db->get('chat_request');
 }

 function Get_user_data($user_id)
 {
  $this->db->where('user_id', $user_id);
  $data = $this->db->get('chat_user');
  $output = array();
  foreach($data->result() as $row)
  {
   $output['first_name'] = $row->first_name;
   $output['last_name'] = $row->last_name;
   $output['email_address'] = $row->email_address;
   $output['profile_picture'] = $row->profile_picture;
  }
  return $output;
 }

 function Update_chat_request($chat_request_id, $data)
 {
  $this->db->where('chat_request_id', $chat_request_id);
  $this->db->update('chat_request', $data);
 }
}
?>


chat_view.php - (Views)


In this view file, we have to write jquery code on accept button click event, and in this jquery, it will send Ajax request to controller method for accpet chat request.



<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Chat Application in Codeigniter</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="<?php echo base_url(); ?>asset/js/jquery.min.js"></script>
  <script src="<?php echo base_url(); ?>asset/js/bootstrap.min.js"></script>
  <link href="<?php echo base_url(); ?>asset/css/bootstrap.min.css" rel="stylesheet" />
  <style type="text/css">
   
   #chat_message_area
   {
    width: 100%;
    height: auto;
    min-height: 80px;
    overflow: auto;
    padding:6px 24px 6px 12px;
    border: 1px solid #CCC;
       border-radius: 3px;
   }

   .notification_circle {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #FF0000;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .online
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #5cb85c;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .offline
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #ccc;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }

  </style>
 </head>
 <body>
  <div clas="container-fluid">
   <br />
   <h2 align="center"><a href="https://www.webslesson.info/2020/03/ajax-jquery-real-time-chat-application-using-codeigniter.html">Chat Application in Codeigniter</a></h2>
   <br />
   <div class="col-md-12" align="right">
    <a href="<?php echo base_url(); ?>google_login/logout">Logout</a>
   </div>
   <div class="col-md-3" style="padding-right:0;">
    <div class="panel panel-default" style="height: 700px; overflow-y: scroll;">
     <div class="panel-heading">Chat with User</div>
     <div class="panel-body" id="chat_user_area">

     </div>
     <input type="hidden" name="hidden_receiver_id_array" id="hidden_receiver_id_array" />
    </div>
   </div>
   <div class="col-md-6" style="padding-left:0; padding-right: 0;">
    <div class="panel panel-default" style="">
     <div class="panel-heading">Chat Area</div>
     <div class="panel-body">
      <div id="chat_header">
       <h2 align="center" style="margin:0; padding-bottom:16px;"><span id="dynamic_title">Welcome <?php echo $this->session->userdata('username'); ?></span></h2>
      </div>
      <div id="chat_body" style="height:406px; overflow-y: scroll;"></div>
      <div id="chat_footer" style="">
       <hr />
       <div class="form-group">
        <div id="chat_message_area" contenteditable class="form-control"></div>
       </div>
       <div class="form-group" align="right">
        <button type="button" name="send_chat" id="send_chat" class="btn btn-success btn-xs" disabled>Send</button>
       </div>
      </div>
     </div>
    </div>
   </div>
   <div class="col-md-3" style="padding-left:0;">
    <div class="panel panel-default" style="height: 300px; overflow-y: scroll;">
     <div class="panel-heading">Search User</div>
     <div class="panel-body">
      <div class="row">
       <div class="col-md-8">
        <input type="text" name="search_user" id="search_user" class="form-control input-sm" placeholder="Search User" />
       </div>
       <div class="col-md-4">
        <button type="button" name="search_button" id="search_button" class="btn btn-primary btn-sm">Search</button>
       </div>
      </div>
      
      <div id="search_user_area"></div>
      
     </div>
    </div>
    <div class="panel panel-default" style="height: 380px; overflow-y: scroll;">
     <div class="panel-heading">Nofication</div>
     <div class="panel-body" id="notification_area">
      
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script>

$(document).ready(function(){

 function loading()
 {
  var output = '<div align="center"><br /><br /><br />';
  output += '<img src="<?php echo base_url(); ?>asset/loading.gif" /> Please wait...</div>';
  return output;
 }

 $(document).on('click', '#search_button', function(){
  var search_query = $.trim($('#search_user').val());
  $('#search_user_area').html('');
  if(search_query != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>chat/search_user",
    method:"POST",
    data:{search_query:search_query},
    dataType:"json",
    beforeSend:function()
    {
     $('#search_user_area').html(loading());
     $('#search_button').attr('disabled', 'disabled');
    },
    success:function(data)
    {
     $('#search_button').attr('disabled', false);
     var output = '<hr />';
     var send_userid = "<?php echo $this->session->userdata('user_id'); ?>";
     if(data.length > 0)
     {
      for(var count = 0; count < data.length; count++)
      {
       output += '<div class="row">';
       output += '<div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="40" /> <small>'+data[count].first_name+' '+data[count].last_name+'</small></div>';
       if(data[count].is_request_send == 'yes')
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-warning btn-xs">Request Sended</button></div>';
       }
       else
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-success btn-xs request_button" id="request_button'+data[count].user_id+'" data-receiver_userid="'+data[count].user_id+'" data-send_userid="'+send_userid+'">Send Request</button></div>';
       }
       output += '</div><hr />';
      }
     }
     else
     {
      output += '<div align="center"><b>No Data Found</b></div>';
     }
     output += '</div>';
     $('#search_user_area').html(output);
    }
   })
  }
 });

 $(document).on('click', '.request_button', function(){
  var id = $(this).attr('id');
  var receiver_userid = $(this).data('receiver_userid');
  var send_userid = $(this).data('send_userid');
  $.ajax({
   url:"<?php echo base_url(); ?>chat/send_request",
   method:"POST",
   data:{receiver_userid:receiver_userid, send_userid:send_userid},
   beforeSend:function()
   {
    $('#'+id).attr('disabled', 'disabled');
   },
   success:function(data)
   {
    $('#'+id).attr('disabled', false);
    $('#'+id).removeClass('btn-success');
    $('#'+id).addClass('btn-warning');
    $('#'+id).text('Request Sended');
   }
  })
 })

 load_notification();

 function load_notification()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_notification",
   method:"POST",
   data:{action:'load_notification'},
   dataType:"json",
   beforeSend:function()
   {
    $('#notification_area').html(loading());
   },
   success:function(data)
   {
    var output = '<hr />';
    //console.log(data.length);
    if(data.length > 0)
    {
     for(var count = 0; count < data.length; count++)
     {
      output += '<div class="row"><div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="35" /> ' + data[count].first_name + ' ' +data[count].last_name + '</div>';

      output += '<div class="col-md-5"><button type="button" name="accept_button" class="btn btn-success btn-xs accept_button" id="accept_button'+data[count].user_id+'" data-chat_request_id="'+data[count].chat_request_id+'">Accept</button></div><hr />';
     }
    }
    else
    {
     output += '<div align="center"><b>No Data Found</b></div>';
    }
    //output += '</div><hr />';
    $('#notification_area').html(output);
   }
  }) 
 }

 $(document).on('click', '.accept_button', function(){
  var id = $(this).attr('id');
  var chat_request_id = $(this).data('chat_request_id');
  $.ajax({
   url:"<?php echo base_url(); ?>chat/accept_request",
   method:"POST",
   data:{chat_request_id:chat_request_id},
   beforeSend:function()
   {
    $('#'+id).attr('disabled','disabled');
   },
   success:function(data)
   {
    $('#'+id).attr('disabled', false);
    $('#'+id).removeClass('btn-success');
    $('#'+id).addClass('btn-warning');
    $('#'+id).text('Accepted');
   }
  })
 });
});

</script>


Load Chat Request Accepted User


In this chat appplication, next step is to load user who has accepted chat request. Once user has accept chat request, then after in this chat system load chat request accepted user at both side. So they can chat with each other. For this feature we have make following method in Codeigniter controller and models class, and in views file we have make following jquery Ajax function.


Chat.php (Controllers)


For load chat request accepted user, in this controller class we have make following method for accept http request for load chat request accepted user.

load_chat_user() - This method has received Ajax request for load chat requested user at both sender and receiver user. This method has received data from model method and send data to Ajax request in json format.



<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Chat extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('chat_model');
  if(!$this->session->userdata('user_id'))
  {
   redirect('google_login/login');
  }
 }

 function index()
 {
  $this->load->view('chat_view');
 }

 function search_user()
 {
  sleep(2);
  if($this->input->post('search_query'))
  {
   $data = $this->chat_model->search_user_data($this->session->userdata('user_id'), $this->input->post('search_query'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $request_status = $this->chat_model->Check_request_status($this->session->userdata('user_id'), $row->user_id);
     $is_request_send = 'yes';
     if($request_status == '')
     {
      $is_request_send = 'no';
     } 
     else
     {
      if($request_status == 'pending')
      {
       $is_request_send = 'yes';
      }
     }
     if($request_status != 'Accept')
     {
      $output[] = array(
       'user_id'  => $row->user_id,
       'first_name' => $row->first_name,
       'last_name'  => $row->last_name,
       'profile_picture'=> $row->profile_picture,
       'is_request_send'=> $is_request_send
      );
     } 
    }
   }
   echo json_encode($output);
  }
 }

 function send_request()
 {
  sleep(2);
  if($this->input->post('send_userid'))
  {
   $data = array(
    'sender_id'  => $this->input->post('send_userid'),
    'receiver_id' => $this->input->post('receiver_userid')
   );
   $this->chat_model->Insert_chat_request($data);
  }
 }

 function load_notification()
 {
  sleep(2);
  if($this->input->post('action'))
  {
   $data = $this->chat_model->Fetch_notification_data($this->session->userdata('user_id'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $userdata = $this->chat_model->Get_user_data($row->sender_id);

     $output[] = array(
      'user_id'  => $row->sender_id,
      'first_name' => $userdata['first_name'],
      'last_name'  => $userdata['last_name'],
      'profile_picture' => $userdata['profile_picture'],
      'chat_request_id' => $row->chat_request_id
     );
    }
   }
   echo json_encode($output);
  }
 }

 function accept_request()
 {
  if($this->input->post('chat_request_id'))
  {
   $update_data = array(
    'chat_request_status' => 'Accept'
   );
   $this->chat_model->Update_chat_request($this->input->post('chat_request_id'), $update_data);
  }
 }

 function load_chat_user()
 {
  sleep(2);
  if($this->input->post('action'))
  {
   $sender_id = $this->session->userdata('user_id');
   $receiver_id = '';
   $data = $this->chat_model->Fetch_chat_user_data($sender_id);
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     if($row->sender_id == $sender_id)
     {
      $receiver_id = $row->receiver_id;
     }
     else
     {
      $receiver_id = $row->sender_id;
     }
     $userdata = $this->chat_model->Get_user_data($receiver_id);
     $output[] = array(
      'receiver_id'  => $receiver_id,
      'first_name'  => $userdata['first_name'],
      'last_name'   => $userdata['last_name'],
      'profile_picture' => $userdata['profile_picture']
     );
    }
   }
   echo json_encode($output);
  }
 }
}
?>


Chat_model.php (Models)


For Mysql database related operation for load chat request accepted user. For in this models class we have make following method.

Fetch_chat_user_data($user_id) - This method will fetch chat request accepted user data from Mysql table and send that data to controller class method.



<?php
class Chat_model extends CI_Model
{
 function search_user_data($user_id, $query)
 {
  $where = "user_id != '".$user_id."' AND (first_name LIKE '%".$query."%' OR last_name LIKE '%".$query."%')";

  $this->db->where($where);

  return $this->db->get('chat_user');
 }

 function Check_request_status($sender_id, $receiver_id)
 {
  $this->db->where('(sender_id = "'.$sender_id.'" OR sender_id = "'.$receiver_id.'")');
  $this->db->where('(receiver_id = "'.$receiver_id.'" OR receiver_id = "'.$sender_id.'")');
  $this->db->order_by('chat_request_id', 'DESC');
  $this->db->limit(1);
  $query = $this->db->get('chat_request');
  if($query->num_rows() > 0)
  {
   foreach($query->result() as $row)
   {
    return $row->chat_request_status;
   }
  }
 }

 function Insert_chat_request($data)
 {
  $this->db->insert('chat_request', $data);
 }

 function Fetch_notification_data($receiver_id)
 {
  $this->db->where('receiver_id', $receiver_id);
  $this->db->where('chat_request_status', 'Pending');
  return $this->db->get('chat_request');
 }

 function Get_user_data($user_id)
 {
  $this->db->where('user_id', $user_id);
  $data = $this->db->get('chat_user');
  $output = array();
  foreach($data->result() as $row)
  {
   $output['first_name'] = $row->first_name;
   $output['last_name'] = $row->last_name;
   $output['email_address'] = $row->email_address;
   $output['profile_picture'] = $row->profile_picture;
  }
  return $output;
 }

 function Update_chat_request($chat_request_id, $data)
 {
  $this->db->where('chat_request_id', $chat_request_id);
  $this->db->update('chat_request', $data);
 }

 function Fetch_chat_user_data($user_id)
 {
  $this->db->where('chat_request_status', 'Accept');
  $this->db->where('(sender_id = "'.$user_id.'" OR receiver_id = "'.$user_id.'")');
  $this->db->order_by('chat_request_id', 'DESC');
  return $this->db->get('chat_request');
 }
}
?>


chat_view.php (Views)


This view file has been display chat request accepted user data in browser in html format. In this file we have make one load_chat_user() jquery function which will send Ajax request to Controller class and received data in json format and convert that data into HTML format and display on web page.



<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Chat Application in Codeigniter</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="<?php echo base_url(); ?>asset/js/jquery.min.js"></script>
  <script src="<?php echo base_url(); ?>asset/js/bootstrap.min.js"></script>
  <link href="<?php echo base_url(); ?>asset/css/bootstrap.min.css" rel="stylesheet" />
  <style type="text/css">
   
   #chat_message_area
   {
    width: 100%;
    height: auto;
    min-height: 80px;
    overflow: auto;
    padding:6px 24px 6px 12px;
    border: 1px solid #CCC;
       border-radius: 3px;
   }

   .notification_circle {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #FF0000;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .online
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #5cb85c;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .offline
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #ccc;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }

  </style>
 </head>
 <body>
  <div clas="container-fluid">
   <br />
   <h2 align="center"><a href="https://www.webslesson.info/2020/03/ajax-jquery-real-time-chat-application-using-codeigniter.html">Chat Application in Codeigniter</a></h2>
   <br />
   <div class="col-md-12" align="right">
    <a href="<?php echo base_url(); ?>google_login/logout">Logout</a>
   </div>
   <div class="col-md-3" style="padding-right:0;">
    <div class="panel panel-default" style="height: 700px; overflow-y: scroll;">
     <div class="panel-heading">Chat with User</div>
     <div class="panel-body" id="chat_user_area">

     </div>
     <input type="hidden" name="hidden_receiver_id_array" id="hidden_receiver_id_array" />
    </div>
   </div>
   <div class="col-md-6" style="padding-left:0; padding-right: 0;">
    <div class="panel panel-default" style="">
     <div class="panel-heading">Chat Area</div>
     <div class="panel-body">
      <div id="chat_header">
       <h2 align="center" style="margin:0; padding-bottom:16px;"><span id="dynamic_title">Welcome <?php echo $this->session->userdata('username'); ?></span></h2>
      </div>
      <div id="chat_body" style="height:406px; overflow-y: scroll;"></div>
      <div id="chat_footer" style="">
       <hr />
       <div class="form-group">
        <div id="chat_message_area" contenteditable class="form-control"></div>
       </div>
       <div class="form-group" align="right">
        <button type="button" name="send_chat" id="send_chat" class="btn btn-success btn-xs" disabled>Send</button>
       </div>
      </div>
     </div>
    </div>
   </div>
   <div class="col-md-3" style="padding-left:0;">
    <div class="panel panel-default" style="height: 300px; overflow-y: scroll;">
     <div class="panel-heading">Search User</div>
     <div class="panel-body">
      <div class="row">
       <div class="col-md-8">
        <input type="text" name="search_user" id="search_user" class="form-control input-sm" placeholder="Search User" />
       </div>
       <div class="col-md-4">
        <button type="button" name="search_button" id="search_button" class="btn btn-primary btn-sm">Search</button>
       </div>
      </div>
      
      <div id="search_user_area"></div>
      
     </div>
    </div>
    <div class="panel panel-default" style="height: 380px; overflow-y: scroll;">
     <div class="panel-heading">Nofication</div>
     <div class="panel-body" id="notification_area">
      
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script>

$(document).ready(function(){

 function loading()
 {
  var output = '<div align="center"><br /><br /><br />';
  output += '<img src="<?php echo base_url(); ?>asset/loading.gif" /> Please wait...</div>';
  return output;
 }

 $(document).on('click', '#search_button', function(){
  var search_query = $.trim($('#search_user').val());
  $('#search_user_area').html('');
  if(search_query != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>chat/search_user",
    method:"POST",
    data:{search_query:search_query},
    dataType:"json",
    beforeSend:function()
    {
     $('#search_user_area').html(loading());
     $('#search_button').attr('disabled', 'disabled');
    },
    success:function(data)
    {
     $('#search_button').attr('disabled', false);
     var output = '<hr />';
     var send_userid = "<?php echo $this->session->userdata('user_id'); ?>";
     if(data.length > 0)
     {
      for(var count = 0; count < data.length; count++)
      {
       output += '<div class="row">';
       output += '<div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="40" /> <small>'+data[count].first_name+' '+data[count].last_name+'</small></div>';
       if(data[count].is_request_send == 'yes')
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-warning btn-xs">Request Sended</button></div>';
       }
       else
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-success btn-xs request_button" id="request_button'+data[count].user_id+'" data-receiver_userid="'+data[count].user_id+'" data-send_userid="'+send_userid+'">Send Request</button></div>';
       }
       output += '</div><hr />';
      }
     }
     else
     {
      output += '<div align="center"><b>No Data Found</b></div>';
     }
     output += '</div>';
     $('#search_user_area').html(output);
    }
   })
  }
 });

 $(document).on('click', '.request_button', function(){
  var id = $(this).attr('id');
  var receiver_userid = $(this).data('receiver_userid');
  var send_userid = $(this).data('send_userid');
  $.ajax({
   url:"<?php echo base_url(); ?>chat/send_request",
   method:"POST",
   data:{receiver_userid:receiver_userid, send_userid:send_userid},
   beforeSend:function()
   {
    $('#'+id).attr('disabled', 'disabled');
   },
   success:function(data)
   {
    $('#'+id).attr('disabled', false);
    $('#'+id).removeClass('btn-success');
    $('#'+id).addClass('btn-warning');
    $('#'+id).text('Request Sended');
   }
  })
 })

 load_notification();

 function load_notification()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_notification",
   method:"POST",
   data:{action:'load_notification'},
   dataType:"json",
   beforeSend:function()
   {
    $('#notification_area').html(loading());
   },
   success:function(data)
   {
    var output = '<hr />';
    //console.log(data.length);
    if(data.length > 0)
    {
     for(var count = 0; count < data.length; count++)
     {
      output += '<div class="row"><div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="35" /> ' + data[count].first_name + ' ' +data[count].last_name + '</div>';

      output += '<div class="col-md-5"><button type="button" name="accept_button" class="btn btn-success btn-xs accept_button" id="accept_button'+data[count].user_id+'" data-chat_request_id="'+data[count].chat_request_id+'">Accept</button></div><hr />';
     }
    }
    else
    {
     output += '<div align="center"><b>No Data Found</b></div>';
    }
    //output += '</div><hr />';
    $('#notification_area').html(output);
   }
  }) 
 }

 $(document).on('click', '.accept_button', function(){
  var id = $(this).attr('id');
  var chat_request_id = $(this).data('chat_request_id');
  $.ajax({
   url:"<?php echo base_url(); ?>chat/accept_request",
   method:"POST",
   data:{chat_request_id:chat_request_id},
   beforeSend:function()
   {
    $('#'+id).attr('disabled','disabled');
   },
   success:function(data)
   {
    $('#'+id).attr('disabled', false);
    $('#'+id).removeClass('btn-success');
    $('#'+id).addClass('btn-warning');
    $('#'+id).text('Accepted');
   }
  })
 });

 load_chat_user();

 function load_chat_user()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_chat_user",
   method:"POST",
   data:{action:'load_chat_user'},
   dataType:'json',
   beforeSend:function()
   {
    $('#chat_user_area').html(loading());
   },
   success:function(data)
   {
    var output = '<div class="list-group">';
    if(data.length > 0)
    {
     var receiver_id_array = '';
     for(var count = 0; count < data.length; count++)
     {
      output += '<a href="javascript:void(0)" class="list-group-item user_chat_list" data-receiver_id="'+data[count].receiver_id+'">';

      output += '<img src="'+data[count].profile_picture+'" class="img-circle" width="35" />';

      output += ' ' + data[count].first_name + ' ' + data[count].last_name;

      receiver_id_array = data[count].receiver_id + ',';
     }
     $('#hidden_receiver_id_array').val(receiver_id_array);
    }
    else
    {
     output += '<div align="center"><b>No Data Found</b></div>';
    }
    output += '</div>';
    $('#chat_user_area').html(output);
   }
  })
 }
});
</script>


Send Chat Messages


Now we have come into right part of this Chat application. In this section you can learn how to send chat messages from one user to another user. For send chat message fuctionality in this Codeigniter Chat app, we have to make following methods in Controller and models class and write jquery ajax script in views file.


Chat.php (Controllers) -


For implement send chat messages in this chat application, we have to make following method in this controller class for handle http request for send chat messages.

send_chat() - This method will accept Ajax request for send chat messages. This method will received data from Ajax request and send that data to models class method for insert into Mysql table and send back request to Ajax request.



<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Chat extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('chat_model');
  if(!$this->session->userdata('user_id'))
  {
   redirect('google_login/login');
  }
 }

 function index()
 {
  $this->load->view('chat_view');
 }

 function search_user()
 {
  sleep(2);
  if($this->input->post('search_query'))
  {
   $data = $this->chat_model->search_user_data($this->session->userdata('user_id'), $this->input->post('search_query'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $request_status = $this->chat_model->Check_request_status($this->session->userdata('user_id'), $row->user_id);
     $is_request_send = 'yes';
     if($request_status == '')
     {
      $is_request_send = 'no';
     } 
     else
     {
      if($request_status == 'pending')
      {
       $is_request_send = 'yes';
      }
     }
     if($request_status != 'Accept')
     {
      $output[] = array(
       'user_id'  => $row->user_id,
       'first_name' => $row->first_name,
       'last_name'  => $row->last_name,
       'profile_picture'=> $row->profile_picture,
       'is_request_send'=> $is_request_send
      );
     } 
    }
   }
   echo json_encode($output);
  }
 }

 function send_request()
 {
  sleep(2);
  if($this->input->post('send_userid'))
  {
   $data = array(
    'sender_id'  => $this->input->post('send_userid'),
    'receiver_id' => $this->input->post('receiver_userid')
   );
   $this->chat_model->Insert_chat_request($data);
  }
 }

 function load_notification()
 {
  sleep(2);
  if($this->input->post('action'))
  {
   $data = $this->chat_model->Fetch_notification_data($this->session->userdata('user_id'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $userdata = $this->chat_model->Get_user_data($row->sender_id);

     $output[] = array(
      'user_id'  => $row->sender_id,
      'first_name' => $userdata['first_name'],
      'last_name'  => $userdata['last_name'],
      'profile_picture' => $userdata['profile_picture'],
      'chat_request_id' => $row->chat_request_id
     );
    }
   }
   echo json_encode($output);
  }
 }

 function accept_request()
 {
  if($this->input->post('chat_request_id'))
  {
   $update_data = array(
    'chat_request_status' => 'Accept'
   );
   $this->chat_model->Update_chat_request($this->input->post('chat_request_id'), $update_data);
  }
 }

 function load_chat_user()
 {
  sleep(2);
  if($this->input->post('action'))
  {
   $sender_id = $this->session->userdata('user_id');
   $receiver_id = '';
   $data = $this->chat_model->Fetch_chat_user_data($sender_id);
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     if($row->sender_id == $sender_id)
     {
      $receiver_id = $row->receiver_id;
     }
     else
     {
      $receiver_id = $row->sender_id;
     }
     $userdata = $this->chat_model->Get_user_data($receiver_id);
     $output[] = array(
      'receiver_id'  => $receiver_id,
      'first_name'  => $userdata['first_name'],
      'last_name'   => $userdata['last_name'],
      'profile_picture' => $userdata['profile_picture']
     );
    }
   }
   echo json_encode($output);
  }
 }

 function send_chat()
 {
  if($this->input->post('receiver_id'))
  {
   $data = array(
    'sender_id'  => $this->session->userdata('user_id'),
    'receiver_id' => $this->input->post('receiver_id'),
    'chat_messages_text' => $this->input->post('chat_message'),
    'chat_messages_status' => 'no',
    'chat_messages_datetime'=> date('Y-m-d H:i:s')
   );

   $this->chat_model->Insert_chat_message($data);
  }
 }
}

?>


Chat_model.php (Models)


In this chat system for make send chat message feature, so for make this feature we have to make following method for handle database operation in this models class.


Insert_chat_message($data) - This method will insert chat data into Mysql table. This method will received data from controller method.



<?php
class Chat_model extends CI_Model
{
 function search_user_data($user_id, $query)
 {
  $where = "user_id != '".$user_id."' AND (first_name LIKE '%".$query."%' OR last_name LIKE '%".$query."%')";

  $this->db->where($where);

  return $this->db->get('chat_user');
 }

 function Check_request_status($sender_id, $receiver_id)
 {
  $this->db->where('(sender_id = "'.$sender_id.'" OR sender_id = "'.$receiver_id.'")');
  $this->db->where('(receiver_id = "'.$receiver_id.'" OR receiver_id = "'.$sender_id.'")');
  $this->db->order_by('chat_request_id', 'DESC');
  $this->db->limit(1);
  $query = $this->db->get('chat_request');
  if($query->num_rows() > 0)
  {
   foreach($query->result() as $row)
   {
    return $row->chat_request_status;
   }
  }
 }

 function Insert_chat_request($data)
 {
  $this->db->insert('chat_request', $data);
 }

 function Fetch_notification_data($receiver_id)
 {
  $this->db->where('receiver_id', $receiver_id);
  $this->db->where('chat_request_status', 'Pending');
  return $this->db->get('chat_request');
 }

 function Get_user_data($user_id)
 {
  $this->db->where('user_id', $user_id);
  $data = $this->db->get('chat_user');
  $output = array();
  foreach($data->result() as $row)
  {
   $output['first_name'] = $row->first_name;
   $output['last_name'] = $row->last_name;
   $output['email_address'] = $row->email_address;
   $output['profile_picture'] = $row->profile_picture;
  }
  return $output;
 }

 function Update_chat_request($chat_request_id, $data)
 {
  $this->db->where('chat_request_id', $chat_request_id);
  $this->db->update('chat_request', $data);
 }

 function Fetch_chat_user_data($user_id)
 {
  $this->db->where('chat_request_status', 'Accept');
  $this->db->where('(sender_id = "'.$user_id.'" OR receiver_id = "'.$user_id.'")');
  $this->db->order_by('chat_request_id', 'DESC');
  return $this->db->get('chat_request');
 }

 function Insert_chat_message($data)
 {
  $this->db->insert('chat_messages', $data);
 }
}
?>


chat_view.php (Views)

For send chat messages, in view file we have to create one division tag with contenteditable attribute property set to true, so user can type chat message in that tag. Then after we have write jQuery code on send chat button. So when user click on button then it will send Ajax request to controller method for send message to another user.



<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Chat Application in Codeigniter</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="<?php echo base_url(); ?>asset/js/jquery.min.js"></script>
  <script src="<?php echo base_url(); ?>asset/js/bootstrap.min.js"></script>
  <link href="<?php echo base_url(); ?>asset/css/bootstrap.min.css" rel="stylesheet" />
  <style type="text/css">
   
   #chat_message_area
   {
    width: 100%;
    height: auto;
    min-height: 80px;
    overflow: auto;
    padding:6px 24px 6px 12px;
    border: 1px solid #CCC;
       border-radius: 3px;
   }

   .notification_circle {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #FF0000;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .online
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #5cb85c;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .offline
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #ccc;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }

  </style>
 </head>
 <body>
  <div clas="container-fluid">
   <br />
   <h2 align="center"><a href="https://www.webslesson.info/2020/03/ajax-jquery-real-time-chat-application-using-codeigniter.html">Chat Application in Codeigniter</a></h2>
   <br />
   <div class="col-md-12" align="right">
    <a href="<?php echo base_url(); ?>google_login/logout">Logout</a>
   </div>
   <div class="col-md-3" style="padding-right:0;">
    <div class="panel panel-default" style="height: 700px; overflow-y: scroll;">
     <div class="panel-heading">Chat with User</div>
     <div class="panel-body" id="chat_user_area">

     </div>
     <input type="hidden" name="hidden_receiver_id_array" id="hidden_receiver_id_array" />
    </div>
   </div>
   <div class="col-md-6" style="padding-left:0; padding-right: 0;">
    <div class="panel panel-default" style="">
     <div class="panel-heading">Chat Area</div>
     <div class="panel-body">
      <div id="chat_header">
       <h2 align="center" style="margin:0; padding-bottom:16px;"><span id="dynamic_title">Welcome <?php echo $this->session->userdata('username'); ?></span></h2>
      </div>
      <div id="chat_body" style="height:406px; overflow-y: scroll;"></div>
      <div id="chat_footer" style="">
       <hr />
       <div class="form-group">
        <div id="chat_message_area" contenteditable class="form-control"></div>
       </div>
       <div class="form-group" align="right">
        <button type="button" name="send_chat" id="send_chat" class="btn btn-success btn-xs" disabled>Send</button>
       </div>
      </div>
     </div>
    </div>
   </div>
   <div class="col-md-3" style="padding-left:0;">
    <div class="panel panel-default" style="height: 300px; overflow-y: scroll;">
     <div class="panel-heading">Search User</div>
     <div class="panel-body">
      <div class="row">
       <div class="col-md-8">
        <input type="text" name="search_user" id="search_user" class="form-control input-sm" placeholder="Search User" />
       </div>
       <div class="col-md-4">
        <button type="button" name="search_button" id="search_button" class="btn btn-primary btn-sm">Search</button>
       </div>
      </div>
      
      <div id="search_user_area"></div>
      
     </div>
    </div>
    <div class="panel panel-default" style="height: 380px; overflow-y: scroll;">
     <div class="panel-heading">Nofication</div>
     <div class="panel-body" id="notification_area">
      
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script>

$(document).ready(function(){

 function loading()
 {
  var output = '<div align="center"><br /><br /><br />';
  output += '<img src="<?php echo base_url(); ?>asset/loading.gif" /> Please wait...</div>';
  return output;
 }

 $(document).on('click', '#search_button', function(){
  var search_query = $.trim($('#search_user').val());
  $('#search_user_area').html('');
  if(search_query != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>chat/search_user",
    method:"POST",
    data:{search_query:search_query},
    dataType:"json",
    beforeSend:function()
    {
     $('#search_user_area').html(loading());
     $('#search_button').attr('disabled', 'disabled');
    },
    success:function(data)
    {
     $('#search_button').attr('disabled', false);
     var output = '<hr />';
     var send_userid = "<?php echo $this->session->userdata('user_id'); ?>";
     if(data.length > 0)
     {
      for(var count = 0; count < data.length; count++)
      {
       output += '<div class="row">';
       output += '<div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="40" /> <small>'+data[count].first_name+' '+data[count].last_name+'</small></div>';
       if(data[count].is_request_send == 'yes')
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-warning btn-xs">Request Sended</button></div>';
       }
       else
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-success btn-xs request_button" id="request_button'+data[count].user_id+'" data-receiver_userid="'+data[count].user_id+'" data-send_userid="'+send_userid+'">Send Request</button></div>';
       }
       output += '</div><hr />';
      }
     }
     else
     {
      output += '<div align="center"><b>No Data Found</b></div>';
     }
     output += '</div>';
     $('#search_user_area').html(output);
    }
   })
  }
 });

 $(document).on('click', '.request_button', function(){
  var id = $(this).attr('id');
  var receiver_userid = $(this).data('receiver_userid');
  var send_userid = $(this).data('send_userid');
  $.ajax({
   url:"<?php echo base_url(); ?>chat/send_request",
   method:"POST",
   data:{receiver_userid:receiver_userid, send_userid:send_userid},
   beforeSend:function()
   {
    $('#'+id).attr('disabled', 'disabled');
   },
   success:function(data)
   {
    $('#'+id).attr('disabled', false);
    $('#'+id).removeClass('btn-success');
    $('#'+id).addClass('btn-warning');
    $('#'+id).text('Request Sended');
   }
  })
 })

 load_notification();

 function load_notification()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_notification",
   method:"POST",
   data:{action:'load_notification'},
   dataType:"json",
   beforeSend:function()
   {
    $('#notification_area').html(loading());
   },
   success:function(data)
   {
    var output = '<hr />';
    //console.log(data.length);
    if(data.length > 0)
    {
     for(var count = 0; count < data.length; count++)
     {
      output += '<div class="row"><div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="35" /> ' + data[count].first_name + ' ' +data[count].last_name + '</div>';

      output += '<div class="col-md-5"><button type="button" name="accept_button" class="btn btn-success btn-xs accept_button" id="accept_button'+data[count].user_id+'" data-chat_request_id="'+data[count].chat_request_id+'">Accept</button></div><hr />';
     }
    }
    else
    {
     output += '<div align="center"><b>No Data Found</b></div>';
    }
    //output += '</div><hr />';
    $('#notification_area').html(output);
   }
  }) 
 }

 $(document).on('click', '.accept_button', function(){
  var id = $(this).attr('id');
  var chat_request_id = $(this).data('chat_request_id');
  $.ajax({
   url:"<?php echo base_url(); ?>chat/accept_request",
   method:"POST",
   data:{chat_request_id:chat_request_id},
   beforeSend:function()
   {
    $('#'+id).attr('disabled','disabled');
   },
   success:function(data)
   {
    $('#'+id).attr('disabled', false);
    $('#'+id).removeClass('btn-success');
    $('#'+id).addClass('btn-warning');
    $('#'+id).text('Accepted');
   }
  })
 });

 load_chat_user();

 function load_chat_user()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_chat_user",
   method:"POST",
   data:{action:'load_chat_user'},
   dataType:'json',
   beforeSend:function()
   {
    $('#chat_user_area').html(loading());
   },
   success:function(data)
   {
    var output = '<div class="list-group">';
    if(data.length > 0)
    {
     var receiver_id_array = '';
     for(var count = 0; count < data.length; count++)
     {
      output += '<a href="javascript:void(0)" class="list-group-item user_chat_list" data-receiver_id="'+data[count].receiver_id+'">';

      output += '<img src="'+data[count].profile_picture+'" class="img-circle" width="35" />';

      output += ' ' + data[count].first_name + ' ' + data[count].last_name;

      receiver_id_array = data[count].receiver_id + ',';
     }
     $('#hidden_receiver_id_array').val(receiver_id_array);
    }
    else
    {
     output += '<div align="center"><b>No Data Found</b></div>';
    }
    output += '</div>';
    $('#chat_user_area').html(output);
   }
  })
 }

 var receiver_id;

 $(document).on('click', '.user_chat_list', function(){
  $('#send_chat').attr('disabled', false);
  receiver_id = $(this).data('receiver_id');
  var receiver_name = $(this).text();
  $('#dynamic_title').text('You Chat with ' + receiver_name);
 });

 $(document).on('click', '#send_chat', function(){
  var chat_message = $.trim($('#chat_message_area').html());
  if(chat_message != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>chat/send_chat",
    method:"POST",
    data:{receiver_id:receiver_id, chat_message:chat_message},
    beforeSend:function()
    {
     $('#send_chat').attr('disabled','disabled');
    },
    success:function(data)
    {
     $('#send_chat').attr('disabled', false);
     $('#chat_message_area').html('');
     var html = '<div class="col-md-10 alert alert-warning">';
     html += chat_message;
     html += '</div>';
     $('#chat_body').append(html);
     $('#chat_body').scrollTop($('#chat_body')[0].scrollHeight);
    }
   });
  }
  else
  {
   alert('Type Something in chat box');
  }
 });

});

</script>


Load Chat Messages


Once Chat message has been send in this chat application. Now we want to display chat history data on web page. So, in this section, we have make Load chat messages feature, which will load chat message on regular interval on web page. For this feature, we have make following method in Codeigniter controller and models class and make requireds changes in views file also.


Chat.php (Controllers)


For load chat message history, we have make followin method in Chat.php controller class.

load_chat_data() - This method will received Ajax request for fetch chat message history data from Mysql database. This method has received data from model method and converted into Array and send back to Ajax request in json string format.



<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Chat extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('chat_model');
  if(!$this->session->userdata('user_id'))
  {
   redirect('google_login/login');
  }
 }

 function index()
 {
  $this->load->view('chat_view');
 }

 function search_user()
 {
  sleep(2);
  if($this->input->post('search_query'))
  {
   $data = $this->chat_model->search_user_data($this->session->userdata('user_id'), $this->input->post('search_query'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $request_status = $this->chat_model->Check_request_status($this->session->userdata('user_id'), $row->user_id);
     $is_request_send = 'yes';
     if($request_status == '')
     {
      $is_request_send = 'no';
     } 
     else
     {
      if($request_status == 'pending')
      {
       $is_request_send = 'yes';
      }
     }
     if($request_status != 'Accept')
     {
      $output[] = array(
       'user_id'  => $row->user_id,
       'first_name' => $row->first_name,
       'last_name'  => $row->last_name,
       'profile_picture'=> $row->profile_picture,
       'is_request_send'=> $is_request_send
      );
     } 
    }
   }
   echo json_encode($output);
  }
 }

 function send_request()
 {
  sleep(2);
  if($this->input->post('send_userid'))
  {
   $data = array(
    'sender_id'  => $this->input->post('send_userid'),
    'receiver_id' => $this->input->post('receiver_userid')
   );
   $this->chat_model->Insert_chat_request($data);
  }
 }

 function load_notification()
 {
  sleep(2);
  if($this->input->post('action'))
  {
   $data = $this->chat_model->Fetch_notification_data($this->session->userdata('user_id'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $userdata = $this->chat_model->Get_user_data($row->sender_id);

     $output[] = array(
      'user_id'  => $row->sender_id,
      'first_name' => $userdata['first_name'],
      'last_name'  => $userdata['last_name'],
      'profile_picture' => $userdata['profile_picture'],
      'chat_request_id' => $row->chat_request_id
     );
    }
   }
   echo json_encode($output);
  }
 }

 function accept_request()
 {
  if($this->input->post('chat_request_id'))
  {
   $update_data = array(
    'chat_request_status' => 'Accept'
   );
   $this->chat_model->Update_chat_request($this->input->post('chat_request_id'), $update_data);
  }
 }

 function load_chat_user()
 {
  sleep(2);
  if($this->input->post('action'))
  {
   $sender_id = $this->session->userdata('user_id');
   $receiver_id = '';
   $data = $this->chat_model->Fetch_chat_user_data($sender_id);
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     if($row->sender_id == $sender_id)
     {
      $receiver_id = $row->receiver_id;
     }
     else
     {
      $receiver_id = $row->sender_id;
     }
     $userdata = $this->chat_model->Get_user_data($receiver_id);
     $output[] = array(
      'receiver_id'  => $receiver_id,
      'first_name'  => $userdata['first_name'],
      'last_name'   => $userdata['last_name'],
      'profile_picture' => $userdata['profile_picture']
     );
    }
   }
   echo json_encode($output);
  }
 }

 function send_chat()
 {
  if($this->input->post('receiver_id'))
  {
   $data = array(
    'sender_id'  => $this->session->userdata('user_id'),
    'receiver_id' => $this->input->post('receiver_id'),
    'chat_messages_text' => $this->input->post('chat_message'),
    'chat_messages_status' => 'no',
    'chat_messages_datetime'=> date('Y-m-d H:i:s')
   );

   $this->chat_model->Insert_chat_message($data);
  }
 }

 function load_chat_data()
 {
  if($this->input->post('receiver_id'))
  {
   $receiver_id = $this->input->post('receiver_id');
   $sender_id = $this->session->userdata('user_id');
   if($this->input->post('update_data') == 'yes')
   {
    $this->chat_model->Update_chat_message_status($sender_id);
   }
   $chat_data = $this->chat_model->Fetch_chat_data($sender_id, $receiver_id);
   if($chat_data->num_rows() > 0)
   {
    foreach($chat_data->result() as $row)
    {
     $message_direction = '';
     if($row->sender_id == $sender_id)
     {
      $message_direction = 'right';
     }
     else
     {
      $message_direction = 'left';
     }
     $date = date('D M Y H:i', strtotime($row->chat_messages_datetime));
     $output[] = array(
      'chat_messages_text' => $row->chat_messages_text,
      'chat_messages_datetime'=> $date,
      'message_direction'  => $message_direction
     );
    }
   }
   echo json_encode($output);
  }
 }
}
?>


Chat_model.php (Models)


For load chat message history, for this feature here in model class we have make following method for handle Mysql database related operation.

Update_chat_message_status($user_id) - This method will update chat message status.

Fetch_chat_data($sender_id, $receiver_id) - This method has fetch chat message conversation between two user from Mysql database.



<?php
class Chat_model extends CI_Model
{
 function search_user_data($user_id, $query)
 {
  $where = "user_id != '".$user_id."' AND (first_name LIKE '%".$query."%' OR last_name LIKE '%".$query."%')";

  $this->db->where($where);

  return $this->db->get('chat_user');
 }

 function Check_request_status($sender_id, $receiver_id)
 {
  $this->db->where('(sender_id = "'.$sender_id.'" OR sender_id = "'.$receiver_id.'")');
  $this->db->where('(receiver_id = "'.$receiver_id.'" OR receiver_id = "'.$sender_id.'")');
  $this->db->order_by('chat_request_id', 'DESC');
  $this->db->limit(1);
  $query = $this->db->get('chat_request');
  if($query->num_rows() > 0)
  {
   foreach($query->result() as $row)
   {
    return $row->chat_request_status;
   }
  }
 }

 function Insert_chat_request($data)
 {
  $this->db->insert('chat_request', $data);
 }

 function Fetch_notification_data($receiver_id)
 {
  $this->db->where('receiver_id', $receiver_id);
  $this->db->where('chat_request_status', 'Pending');
  return $this->db->get('chat_request');
 }

 function Get_user_data($user_id)
 {
  $this->db->where('user_id', $user_id);
  $data = $this->db->get('chat_user');
  $output = array();
  foreach($data->result() as $row)
  {
   $output['first_name'] = $row->first_name;
   $output['last_name'] = $row->last_name;
   $output['email_address'] = $row->email_address;
   $output['profile_picture'] = $row->profile_picture;
  }
  return $output;
 }

 function Update_chat_request($chat_request_id, $data)
 {
  $this->db->where('chat_request_id', $chat_request_id);
  $this->db->update('chat_request', $data);
 }

 function Fetch_chat_user_data($user_id)
 {
  $this->db->where('chat_request_status', 'Accept');
  $this->db->where('(sender_id = "'.$user_id.'" OR receiver_id = "'.$user_id.'")');
  $this->db->order_by('chat_request_id', 'DESC');
  return $this->db->get('chat_request');
 }

 function Insert_chat_message($data)
 {
  $this->db->insert('chat_messages', $data);
 }

 function Update_chat_message_status($user_id)
 {
  $data = array(
   'chat_messages_status'  => 'yes'
  );
  $this->db->where('receiver_id', $user_id);
  $this->db->where('chat_messages_status', 'no');
  $this->db->update('chat_messages', $data);
 }

 function Fetch_chat_data($sender_id, $receiver_id)
 {
  $this->db->where('(sender_id = "'.$sender_id.'" OR sender_id = "'.$receiver_id.'")');
  $this->db->where('(receiver_id = "'.$receiver_id.'" OR receiver_id = "'.$sender_id.'")');
  $this->db->order_by('chat_messages_id', 'ASC');
  return $this->db->get('chat_messages');
 }
}
?>


chat_view.php (Views)


This view file will display chat history message on web page. When user has been click on any user name, then that chat message conversation between login user and that user chat message will be display on web page. And after this by using setInterval() function, chat message data will be updated on every 5 second.



<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Chat Application in Codeigniter</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="<?php echo base_url(); ?>asset/js/jquery.min.js"></script>
  <script src="<?php echo base_url(); ?>asset/js/bootstrap.min.js"></script>
  <link href="<?php echo base_url(); ?>asset/css/bootstrap.min.css" rel="stylesheet" />
  <style type="text/css">
   
   #chat_message_area
   {
    width: 100%;
    height: auto;
    min-height: 80px;
    overflow: auto;
    padding:6px 24px 6px 12px;
    border: 1px solid #CCC;
       border-radius: 3px;
   }

   .notification_circle {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #FF0000;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .online
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #5cb85c;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .offline
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #ccc;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }

  </style>
 </head>
 <body>
  <div clas="container-fluid">
   <br />
   <h2 align="center"><a href="https://www.webslesson.info/2020/03/ajax-jquery-real-time-chat-application-using-codeigniter.html">Chat Application in Codeigniter</a></h2>
   <br />
   <div class="col-md-12" align="right">
    <a href="<?php echo base_url(); ?>google_login/logout">Logout</a>
   </div>
   <div class="col-md-3" style="padding-right:0;">
    <div class="panel panel-default" style="height: 700px; overflow-y: scroll;">
     <div class="panel-heading">Chat with User</div>
     <div class="panel-body" id="chat_user_area">

     </div>
     <input type="hidden" name="hidden_receiver_id_array" id="hidden_receiver_id_array" />
    </div>
   </div>
   <div class="col-md-6" style="padding-left:0; padding-right: 0;">
    <div class="panel panel-default" style="">
     <div class="panel-heading">Chat Area</div>
     <div class="panel-body">
      <div id="chat_header">
       <h2 align="center" style="margin:0; padding-bottom:16px;"><span id="dynamic_title">Welcome <?php echo $this->session->userdata('username'); ?></span></h2>
      </div>
      <div id="chat_body" style="height:406px; overflow-y: scroll;"></div>
      <div id="chat_footer" style="">
       <hr />
       <div class="form-group">
        <div id="chat_message_area" contenteditable class="form-control"></div>
       </div>
       <div class="form-group" align="right">
        <button type="button" name="send_chat" id="send_chat" class="btn btn-success btn-xs" disabled>Send</button>
       </div>
      </div>
     </div>
    </div>
   </div>
   <div class="col-md-3" style="padding-left:0;">
    <div class="panel panel-default" style="height: 300px; overflow-y: scroll;">
     <div class="panel-heading">Search User</div>
     <div class="panel-body">
      <div class="row">
       <div class="col-md-8">
        <input type="text" name="search_user" id="search_user" class="form-control input-sm" placeholder="Search User" />
       </div>
       <div class="col-md-4">
        <button type="button" name="search_button" id="search_button" class="btn btn-primary btn-sm">Search</button>
       </div>
      </div>
      
      <div id="search_user_area"></div>
      
     </div>
    </div>
    <div class="panel panel-default" style="height: 380px; overflow-y: scroll;">
     <div class="panel-heading">Nofication</div>
     <div class="panel-body" id="notification_area">
      
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script>

$(document).ready(function(){

 function loading()
 {
  var output = '<div align="center"><br /><br /><br />';
  output += '<img src="<?php echo base_url(); ?>asset/loading.gif" /> Please wait...</div>';
  return output;
 }

 $(document).on('click', '#search_button', function(){
  var search_query = $.trim($('#search_user').val());
  $('#search_user_area').html('');
  if(search_query != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>chat/search_user",
    method:"POST",
    data:{search_query:search_query},
    dataType:"json",
    beforeSend:function()
    {
     $('#search_user_area').html(loading());
     $('#search_button').attr('disabled', 'disabled');
    },
    success:function(data)
    {
     $('#search_button').attr('disabled', false);
     var output = '<hr />';
     var send_userid = "<?php echo $this->session->userdata('user_id'); ?>";
     if(data.length > 0)
     {
      for(var count = 0; count < data.length; count++)
      {
       output += '<div class="row">';
       output += '<div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="40" /> <small>'+data[count].first_name+' '+data[count].last_name+'</small></div>';
       if(data[count].is_request_send == 'yes')
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-warning btn-xs">Request Sended</button></div>';
       }
       else
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-success btn-xs request_button" id="request_button'+data[count].user_id+'" data-receiver_userid="'+data[count].user_id+'" data-send_userid="'+send_userid+'">Send Request</button></div>';
       }
       output += '</div><hr />';
      }
     }
     else
     {
      output += '<div align="center"><b>No Data Found</b></div>';
     }
     output += '</div>';
     $('#search_user_area').html(output);
    }
   })
  }
 });

 $(document).on('click', '.request_button', function(){
  var id = $(this).attr('id');
  var receiver_userid = $(this).data('receiver_userid');
  var send_userid = $(this).data('send_userid');
  $.ajax({
   url:"<?php echo base_url(); ?>chat/send_request",
   method:"POST",
   data:{receiver_userid:receiver_userid, send_userid:send_userid},
   beforeSend:function()
   {
    $('#'+id).attr('disabled', 'disabled');
   },
   success:function(data)
   {
    $('#'+id).attr('disabled', false);
    $('#'+id).removeClass('btn-success');
    $('#'+id).addClass('btn-warning');
    $('#'+id).text('Request Sended');
   }
  })
 })

 load_notification();

 function load_notification()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_notification",
   method:"POST",
   data:{action:'load_notification'},
   dataType:"json",
   beforeSend:function()
   {
    $('#notification_area').html(loading());
   },
   success:function(data)
   {
    var output = '<hr />';
    //console.log(data.length);
    if(data.length > 0)
    {
     for(var count = 0; count < data.length; count++)
     {
      output += '<div class="row"><div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="35" /> ' + data[count].first_name + ' ' +data[count].last_name + '</div>';

      output += '<div class="col-md-5"><button type="button" name="accept_button" class="btn btn-success btn-xs accept_button" id="accept_button'+data[count].user_id+'" data-chat_request_id="'+data[count].chat_request_id+'">Accept</button></div><hr />';
     }
    }
    else
    {
     output += '<div align="center"><b>No Data Found</b></div>';
    }
    //output += '</div><hr />';
    $('#notification_area').html(output);
   }
  }) 
 }

 $(document).on('click', '.accept_button', function(){
  var id = $(this).attr('id');
  var chat_request_id = $(this).data('chat_request_id');
  $.ajax({
   url:"<?php echo base_url(); ?>chat/accept_request",
   method:"POST",
   data:{chat_request_id:chat_request_id},
   beforeSend:function()
   {
    $('#'+id).attr('disabled','disabled');
   },
   success:function(data)
   {
    $('#'+id).attr('disabled', false);
    $('#'+id).removeClass('btn-success');
    $('#'+id).addClass('btn-warning');
    $('#'+id).text('Accepted');
   }
  })
 });

 load_chat_user();

 function load_chat_user()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_chat_user",
   method:"POST",
   data:{action:'load_chat_user'},
   dataType:'json',
   beforeSend:function()
   {
    $('#chat_user_area').html(loading());
   },
   success:function(data)
   {
    var output = '<div class="list-group">';
    if(data.length > 0)
    {
     var receiver_id_array = '';
     for(var count = 0; count < data.length; count++)
     {
      output += '<a href="javascript:void(0)" class="list-group-item user_chat_list" data-receiver_id="'+data[count].receiver_id+'">';

      output += '<img src="'+data[count].profile_picture+'" class="img-circle" width="35" />';

      output += ' ' + data[count].first_name + ' ' + data[count].last_name;

      receiver_id_array = data[count].receiver_id + ',';
     }
     $('#hidden_receiver_id_array').val(receiver_id_array);
    }
    else
    {
     output += '<div align="center"><b>No Data Found</b></div>';
    }
    output += '</div>';
    $('#chat_user_area').html(output);
   }
  })
 }

 var receiver_id;

 $(document).on('click', '.user_chat_list', function(){
  $('#send_chat').attr('disabled', false);
  receiver_id = $(this).data('receiver_id');
  var receiver_name = $(this).text();
  $('#dynamic_title').text('You Chat with ' + receiver_name);
  load_chat_data(receiver_id, 'yes');
 });

 $(document).on('click', '#send_chat', function(){
  var chat_message = $.trim($('#chat_message_area').html());
  if(chat_message != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>chat/send_chat",
    method:"POST",
    data:{receiver_id:receiver_id, chat_message:chat_message},
    beforeSend:function()
    {
     $('#send_chat').attr('disabled','disabled');
    },
    success:function(data)
    {
     $('#send_chat').attr('disabled', false);
     $('#chat_message_area').html('');
     var html = '<div class="col-md-10 alert alert-warning">';
     html += chat_message;
     html += '</div>';
     $('#chat_body').append(html);
     $('#chat_body').scrollTop($('#chat_body')[0].scrollHeight);
    }
   });
  }
  else
  {
   alert('Type Something in chat box');
  }
 });

 function load_chat_data(receiver_id, update_data)
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_chat_data",
   method:"POST",
   data:{receiver_id:receiver_id, update_data:update_data},
   dataType:"json",
   success:function(data)
   {
    var html = '';
    for(var count = 0; count < data.length; count++)
    {
     html += '<div class="row" style="margin-left:0; margin-right:0">';
     if(data[count].message_direction == 'right')
     {
      html += '<div align="left"><span class="text-muted"><small><b>'+data[count].chat_messages_datetime+'</b></small></span></div>';

      html += '<div class="col-md-10 alert alert-warning">';
     }
     else
     {
      html += '<div align="right"><span class="text-muted"><small><b>'+data[count].chat_messages_datetime+'</b></small></span></div>';
      html += '<div class="col-md-2">&nbsp;</div>';
      html += '<div class="col-md-10 alert alert-info">';
     }
     html += data[count].chat_messages_text + '</div></div>';
    }
    $('#chat_body').html(html);
    $('#chat_body').scrollTop($('#chat_body')[0].scrollHeight);
   }
  })
 }

 setInterval(function(){
  if(receiver_id > 0)
  {
   load_chat_data(receiver_id, 'yes');
  }
 }, 5000);
});
</script>





Display Unread Messsage Notification


After send message to one user to another user, but that user is not login into system. So when he or she login into system then at that time they can see how many messages they have receiver from each user. For this feature, we have make following changes in this Chat application code.


Chat.php (Controllers)



<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Chat extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('chat_model');
  date_default_timezone_set("Asia/Calcutta");
  if(!$this->session->userdata('user_id'))
  {
   redirect('google_login/login');
  }
 }

 function index()
 {
  $this->load->view('chat_view');
 }

 function search_user()
 {
  sleep(2);
  if($this->input->post('search_query'))
  {
   $data = $this->chat_model->search_user_data($this->session->userdata('user_id'), $this->input->post('search_query'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $request_status = $this->chat_model->Check_request_status($this->session->userdata('user_id'), $row->user_id);
     $is_request_send = 'yes';
     if($request_status == '')
     {
      $is_request_send = 'no';
     } 
     else
     {
      if($request_status == 'pending')
      {
       $is_request_send = 'yes';
      }
     }
     if($request_status != 'Accept')
     {
      $output[] = array(
       'user_id'  => $row->user_id,
       'first_name' => $row->first_name,
       'last_name'  => $row->last_name,
       'profile_picture'=> $row->profile_picture,
       'is_request_send'=> $is_request_send
      );
     } 
    }
   }
   echo json_encode($output);
  }
 }

 function send_request()
 {
  sleep(2);
  if($this->input->post('send_userid'))
  {
   $data = array(
    'sender_id'  => $this->input->post('send_userid'),
    'receiver_id' => $this->input->post('receiver_userid')
   );
   $this->chat_model->Insert_chat_request($data);
  }
 }

 function load_notification()
 {
  sleep(2);
  if($this->input->post('action'))
  {
   $data = $this->chat_model->Fetch_notification_data($this->session->userdata('user_id'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $userdata = $this->chat_model->Get_user_data($row->sender_id);

     $output[] = array(
      'user_id'  => $row->sender_id,
      'first_name' => $userdata['first_name'],
      'last_name'  => $userdata['last_name'],
      'profile_picture' => $userdata['profile_picture'],
      'chat_request_id' => $row->chat_request_id
     );
    }
   }
   echo json_encode($output);
  }
 }

 function accept_request()
 {
  if($this->input->post('chat_request_id'))
  {
   $update_data = array(
    'chat_request_status' => 'Accept'
   );
   $this->chat_model->Update_chat_request($this->input->post('chat_request_id'), $update_data);
  }
 }

 function load_chat_user()
 {
  sleep(2);
  if($this->input->post('action'))
  {
   $sender_id = $this->session->userdata('user_id');
   $receiver_id = '';
   $data = $this->chat_model->Fetch_chat_user_data($sender_id);
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     if($row->sender_id == $sender_id)
     {
      $receiver_id = $row->receiver_id;
     }
     else
     {
      $receiver_id = $row->sender_id;
     }
     $userdata = $this->chat_model->Get_user_data($receiver_id);
     $output[] = array(
      'receiver_id'  => $receiver_id,
      'first_name'  => $userdata['first_name'],
      'last_name'   => $userdata['last_name'],
      'profile_picture' => $userdata['profile_picture']
     );
    }
   }
   echo json_encode($output);
  }
 }

 function send_chat()
 {
  if($this->input->post('receiver_id'))
  {
   $data = array(
    'sender_id'  => $this->session->userdata('user_id'),
    'receiver_id' => $this->input->post('receiver_id'),
    'chat_messages_text' => $this->input->post('chat_message'),
    'chat_messages_status' => 'no',
    'chat_messages_datetime'=> date('Y-m-d H:i:s')
   );

   $this->chat_model->Insert_chat_message($data);
  }
 }

 function load_chat_data()
 {
  if($this->input->post('receiver_id'))
  {
   $receiver_id = $this->input->post('receiver_id');
   $sender_id = $this->session->userdata('user_id');
   if($this->input->post('update_data') == 'yes')
   {
    $this->chat_model->Update_chat_message_status($sender_id);
   }
   $chat_data = $this->chat_model->Fetch_chat_data($sender_id, $receiver_id);
   if($chat_data->num_rows() > 0)
   {
    foreach($chat_data->result() as $row)
    {
     $message_direction = '';
     if($row->sender_id == $sender_id)
     {
      $message_direction = 'right';
     }
     else
     {
      $message_direction = 'left';
     }
     $date = date('D M Y H:i', strtotime($row->chat_messages_datetime));
     $output[] = array(
      'chat_messages_text' => $row->chat_messages_text,
      'chat_messages_datetime'=> $date,
      'message_direction'  => $message_direction
     );
    }
   }
   echo json_encode($output);
  }
 }

 function check_chat_notification()
 {
  if($this->input->post('user_id_array'))
  {
   $receiver_id = $this->session->userdata('user_id');

   $this->chat_model->Update_login_data();

   $user_id_array = explode(",", $this->input->post('user_id_array'));

   $output = array();

   foreach($user_id_array as $sender_id)
   {
    if($sender_id != '')
    {
     $output[] = array(
      'user_id'  => $sender_id,
      'total_notification' => $this->chat_model->Count_chat_notification($sender_id, $receiver_id)
     );
    }
   }
   echo json_encode($output);
  }
 }
}
?>


Chat_model.php (Models)



<?php
class Chat_model extends CI_Model
{
 function search_user_data($user_id, $query)
 {
  $where = "user_id != '".$user_id."' AND (first_name LIKE '%".$query."%' OR last_name LIKE '%".$query."%')";

  $this->db->where($where);

  return $this->db->get('chat_user');
 }

 function Check_request_status($sender_id, $receiver_id)
 {
  $this->db->where('(sender_id = "'.$sender_id.'" OR sender_id = "'.$receiver_id.'")');
  $this->db->where('(receiver_id = "'.$receiver_id.'" OR receiver_id = "'.$sender_id.'")');
  $this->db->order_by('chat_request_id', 'DESC');
  $this->db->limit(1);
  $query = $this->db->get('chat_request');
  if($query->num_rows() > 0)
  {
   foreach($query->result() as $row)
   {
    return $row->chat_request_status;
   }
  }
 }

 function Insert_chat_request($data)
 {
  $this->db->insert('chat_request', $data);
 }

 function Fetch_notification_data($receiver_id)
 {
  $this->db->where('receiver_id', $receiver_id);
  $this->db->where('chat_request_status', 'Pending');
  return $this->db->get('chat_request');
 }

 function Get_user_data($user_id)
 {
  $this->db->where('user_id', $user_id);
  $data = $this->db->get('chat_user');
  $output = array();
  foreach($data->result() as $row)
  {
   $output['first_name'] = $row->first_name;
   $output['last_name'] = $row->last_name;
   $output['email_address'] = $row->email_address;
   $output['profile_picture'] = $row->profile_picture;
  }
  return $output;
 }

 function Update_chat_request($chat_request_id, $data)
 {
  $this->db->where('chat_request_id', $chat_request_id);
  $this->db->update('chat_request', $data);
 }

 function Fetch_chat_user_data($user_id)
 {
  $this->db->where('chat_request_status', 'Accept');
  $this->db->where('(sender_id = "'.$user_id.'" OR receiver_id = "'.$user_id.'")');
  $this->db->order_by('chat_request_id', 'DESC');
  return $this->db->get('chat_request');
 }

 function Insert_chat_message($data)
 {
  $this->db->insert('chat_messages', $data);
 }

 function Update_chat_message_status($user_id)
 {
  $data = array(
   'chat_messages_status'  => 'yes'
  );
  $this->db->where('receiver_id', $user_id);
  $this->db->where('chat_messages_status', 'no');
  $this->db->update('chat_messages', $data);
 }

 function Fetch_chat_data($sender_id, $receiver_id)
 {
  $this->db->where('(sender_id = "'.$sender_id.'" OR sender_id = "'.$receiver_id.'")');
  $this->db->where('(receiver_id = "'.$receiver_id.'" OR receiver_id = "'.$sender_id.'")');
  $this->db->order_by('chat_messages_id', 'ASC');
  return $this->db->get('chat_messages');
 }

 function Count_chat_notification($sender_id, $receiver_id)
 {
  $this->db->where('sender_id', $sender_id);
  $this->db->where('receiver_id', $receiver_id);
  $this->db->where('chat_messages_status', 'no');
  $query = $this->db->get('chat_messages');
  return $query->num_rows();
 }
}
?>


chat_view.php (Views)



<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Chat Application in Codeigniter</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="<?php echo base_url(); ?>asset/js/jquery.min.js"></script>
  <script src="<?php echo base_url(); ?>asset/js/bootstrap.min.js"></script>
  <link href="<?php echo base_url(); ?>asset/css/bootstrap.min.css" rel="stylesheet" />
  <style type="text/css">
   
   #chat_message_area
   {
    width: 100%;
    height: auto;
    min-height: 80px;
    overflow: auto;
    padding:6px 24px 6px 12px;
    border: 1px solid #CCC;
       border-radius: 3px;
   }

   .notification_circle {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #FF0000;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .online
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #5cb85c;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .offline
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #ccc;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }

  </style>
 </head>
 <body>
  <div clas="container-fluid">
   <br />
   <h2 align="center"><a href="https://www.webslesson.info/2020/03/ajax-jquery-real-time-chat-application-using-codeigniter.html">Chat Application in Codeigniter</a></h2>
   <br />
   <div class="col-md-12" align="right">
    <a href="<?php echo base_url(); ?>google_login/logout">Logout</a>
   </div>
   <div class="col-md-3" style="padding-right:0;">
    <div class="panel panel-default" style="height: 700px; overflow-y: scroll;">
     <div class="panel-heading">Chat with User</div>
     <div class="panel-body" id="chat_user_area">

     </div>
     <input type="hidden" name="hidden_receiver_id_array" id="hidden_receiver_id_array" />
    </div>
   </div>
   <div class="col-md-6" style="padding-left:0; padding-right: 0;">
    <div class="panel panel-default" style="">
     <div class="panel-heading">Chat Area</div>
     <div class="panel-body">
      <div id="chat_header">
       <h2 align="center" style="margin:0; padding-bottom:16px;"><span id="dynamic_title">Welcome <?php echo $this->session->userdata('username'); ?></span></h2>
      </div>
      <div id="chat_body" style="height:406px; overflow-y: scroll;"></div>
      <div id="chat_footer" style="">
       <hr />
       <div class="form-group">
        <div id="chat_message_area" contenteditable class="form-control"></div>
       </div>
       <div class="form-group" align="right">
        <button type="button" name="send_chat" id="send_chat" class="btn btn-success btn-xs" disabled>Send</button>
       </div>
      </div>
     </div>
    </div>
   </div>
   <div class="col-md-3" style="padding-left:0;">
    <div class="panel panel-default" style="height: 300px; overflow-y: scroll;">
     <div class="panel-heading">Search User</div>
     <div class="panel-body">
      <div class="row">
       <div class="col-md-8">
        <input type="text" name="search_user" id="search_user" class="form-control input-sm" placeholder="Search User" />
       </div>
       <div class="col-md-4">
        <button type="button" name="search_button" id="search_button" class="btn btn-primary btn-sm">Search</button>
       </div>
      </div>
      
      <div id="search_user_area"></div>
      
     </div>
    </div>
    <div class="panel panel-default" style="height: 380px; overflow-y: scroll;">
     <div class="panel-heading">Nofication</div>
     <div class="panel-body" id="notification_area">
      
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script>

$(document).ready(function(){

 function loading()
 {
  var output = '<div align="center"><br /><br /><br />';
  output += '<img src="<?php echo base_url(); ?>asset/loading.gif" /> Please wait...</div>';
  return output;
 }

 $(document).on('click', '#search_button', function(){
  var search_query = $.trim($('#search_user').val());
  $('#search_user_area').html('');
  if(search_query != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>chat/search_user",
    method:"POST",
    data:{search_query:search_query},
    dataType:"json",
    beforeSend:function()
    {
     $('#search_user_area').html(loading());
     $('#search_button').attr('disabled', 'disabled');
    },
    success:function(data)
    {
     $('#search_button').attr('disabled', false);
     var output = '<hr />';
     var send_userid = "<?php echo $this->session->userdata('user_id'); ?>";
     if(data.length > 0)
     {
      for(var count = 0; count < data.length; count++)
      {
       output += '<div class="row">';
       output += '<div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="40" /> <small>'+data[count].first_name+' '+data[count].last_name+'</small></div>';
       if(data[count].is_request_send == 'yes')
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-warning btn-xs">Request Sended</button></div>';
       }
       else
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-success btn-xs request_button" id="request_button'+data[count].user_id+'" data-receiver_userid="'+data[count].user_id+'" data-send_userid="'+send_userid+'">Send Request</button></div>';
       }
       output += '</div><hr />';
      }
     }
     else
     {
      output += '<div align="center"><b>No Data Found</b></div>';
     }
     output += '</div>';
     $('#search_user_area').html(output);
    }
   })
  }
 });

 $(document).on('click', '.request_button', function(){
  var id = $(this).attr('id');
  var receiver_userid = $(this).data('receiver_userid');
  var send_userid = $(this).data('send_userid');
  $.ajax({
   url:"<?php echo base_url(); ?>chat/send_request",
   method:"POST",
   data:{receiver_userid:receiver_userid, send_userid:send_userid},
   beforeSend:function()
   {
    $('#'+id).attr('disabled', 'disabled');
   },
   success:function(data)
   {
    $('#'+id).attr('disabled', false);
    $('#'+id).removeClass('btn-success');
    $('#'+id).addClass('btn-warning');
    $('#'+id).text('Request Sended');
   }
  })
 })

 load_notification();

 function load_notification()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_notification",
   method:"POST",
   data:{action:'load_notification'},
   dataType:"json",
   beforeSend:function()
   {
    $('#notification_area').html(loading());
   },
   success:function(data)
   {
    var output = '<hr />';
    //console.log(data.length);
    if(data.length > 0)
    {
     for(var count = 0; count < data.length; count++)
     {
      output += '<div class="row"><div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="35" /> ' + data[count].first_name + ' ' +data[count].last_name + '</div>';

      output += '<div class="col-md-5"><button type="button" name="accept_button" class="btn btn-success btn-xs accept_button" id="accept_button'+data[count].user_id+'" data-chat_request_id="'+data[count].chat_request_id+'">Accept</button></div><hr />';
     }
    }
    else
    {
     output += '<div align="center"><b>No Data Found</b></div>';
    }
    //output += '</div><hr />';
    $('#notification_area').html(output);
   }
  }) 
 }

 $(document).on('click', '.accept_button', function(){
  var id = $(this).attr('id');
  var chat_request_id = $(this).data('chat_request_id');
  $.ajax({
   url:"<?php echo base_url(); ?>chat/accept_request",
   method:"POST",
   data:{chat_request_id:chat_request_id},
   beforeSend:function()
   {
    $('#'+id).attr('disabled','disabled');
   },
   success:function(data)
   {
    $('#'+id).attr('disabled', false);
    $('#'+id).removeClass('btn-success');
    $('#'+id).addClass('btn-warning');
    $('#'+id).text('Accepted');
   }
  })
 });

 load_chat_user();

 function load_chat_user()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_chat_user",
   method:"POST",
   data:{action:'load_chat_user'},
   dataType:'json',
   beforeSend:function()
   {
    $('#chat_user_area').html(loading());
   },
   success:function(data)
   {
    var output = '<div class="list-group">';
    if(data.length > 0)
    {
     var receiver_id_array = '';
     for(var count = 0; count < data.length; count++)
     {
      output += '<a href="javascript:void(0)" class="list-group-item user_chat_list" data-receiver_id="'+data[count].receiver_id+'">';

      output += '<img src="'+data[count].profile_picture+'" class="img-circle" width="35" />';

      output += ' ' + data[count].first_name + ' ' + data[count].last_name;

      output += '&nbsp;<span id="chat_notification_'+data[count].receiver_id + '"></span>';

      receiver_id_array += data[count].receiver_id + ',';
     }
     $('#hidden_receiver_id_array').val(receiver_id_array);
    }
    else
    {
     output += '<div align="center"><b>No Data Found</b></div>';
    }
    output += '</div>';
    $('#chat_user_area').html(output);
   }
  })
 }

 var receiver_id;

 $(document).on('click', '.user_chat_list', function(){
  $('#send_chat').attr('disabled', false);
  receiver_id = $(this).data('receiver_id');
  var receiver_name = $(this).text();
  $('#dynamic_title').text('You Chat with ' + receiver_name);
  load_chat_data(receiver_id, 'yes');
 });

 $(document).on('click', '#send_chat', function(){
  var chat_message = $.trim($('#chat_message_area').html());
  if(chat_message != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>chat/send_chat",
    method:"POST",
    data:{receiver_id:receiver_id, chat_message:chat_message},
    beforeSend:function()
    {
     $('#send_chat').attr('disabled','disabled');
    },
    success:function(data)
    {
     $('#send_chat').attr('disabled', false);
     $('#chat_message_area').html('');
     var html = '<div class="col-md-10 alert alert-warning">';
     html += chat_message;
     html += '</div>';
     $('#chat_body').append(html);
     $('#chat_body').scrollTop($('#chat_body')[0].scrollHeight);
    }
   });
  }
  else
  {
   alert('Type Something in chat box');
  }
 });

 function load_chat_data(receiver_id, update_data)
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_chat_data",
   method:"POST",
   data:{receiver_id:receiver_id, update_data:update_data},
   dataType:"json",
   success:function(data)
   {
    var html = '';
    for(var count = 0; count < data.length; count++)
    {
     html += '<div class="row" style="margin-left:0; margin-right:0">';
     if(data[count].message_direction == 'right')
     {
      html += '<div align="left"><span class="text-muted"><small><b>'+data[count].chat_messages_datetime+'</b></small></span></div>';

      html += '<div class="col-md-10 alert alert-warning">';
     }
     else
     {
      html += '<div align="right"><span class="text-muted"><small><b>'+data[count].chat_messages_datetime+'</b></small></span></div>';
      html += '<div class="col-md-2">&nbsp;</div>';
      html += '<div class="col-md-10 alert alert-info">';
     }
     html += data[count].chat_messages_text + '</div></div>';
    }
    $('#chat_body').html(html);
    $('#chat_body').scrollTop($('#chat_body')[0].scrollHeight);
   }
  })
 }

 setInterval(function(){
  if(receiver_id > 0)
  {
   load_chat_data(receiver_id, 'yes');
  }
  check_chat_notification();
 }, 5000);

 function check_chat_notification(receiver_id)
 {
  var user_id_array = $('#hidden_receiver_id_array').val();

  ///
  var is_type = 'no';
  if(receiver_id > 0)
  {
   if($.trim($('#chat_message_area').text()) != '')
   {
    is_type = 'yes';
   }
  }
  ///

  $.ajax({
   url:"<?php echo base_url(); ?>chat/check_chat_notification",
   method:"POST",
   data:{user_id_array:user_id_array, is_type:is_type, receiver_id:receiver_id},
   dataType:"json",
   success:function(data)
   {
    if(data.length > 0)
    {
     for(var count = 0; count < data.length; count++)
     {
      var html = '';
      if(data[count].total_notification > 0)
      {
       if(data[count].user_id != receiver_id)
       {
        html = '<span class="notification_circle">'+data[count].total_notification+'</span>';
       }
      }

      $('#chat_notification_'+data[count].user_id).html(html);
     }
    }
   }
  })
 }

});

</script>


Chat User Online or Offline Status


In this section, we have one more feature in this Codeigniter Chat Application. In this section, we have add functionality like display user if online or offline in this chat application. If User is on chat page, then that user status will be display online, and if User is logout from system or not on chat page then that User status will be display offline. For this feature, we have make following chages in Model Views and Controller file.



Chat.php (Controllers)



<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Chat extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('chat_model');
  date_default_timezone_set("Asia/Calcutta");
  if(!$this->session->userdata('user_id'))
  {
   redirect('google_login/login');
  }
 }

 function index()
 {
  $this->load->view('chat_view');
 }

 function search_user()
 {
  sleep(2);
  if($this->input->post('search_query'))
  {
   $data = $this->chat_model->search_user_data($this->session->userdata('user_id'), $this->input->post('search_query'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $request_status = $this->chat_model->Check_request_status($this->session->userdata('user_id'), $row->user_id);
     $is_request_send = 'yes';
     if($request_status == '')
     {
      $is_request_send = 'no';
     } 
     else
     {
      if($request_status == 'pending')
      {
       $is_request_send = 'yes';
      }
     }
     if($request_status != 'Accept')
     {
      $output[] = array(
       'user_id'  => $row->user_id,
       'first_name' => $row->first_name,
       'last_name'  => $row->last_name,
       'profile_picture'=> $row->profile_picture,
       'is_request_send'=> $is_request_send
      );
     } 
    }
   }
   echo json_encode($output);
  }
 }

 function send_request()
 {
  sleep(2);
  if($this->input->post('send_userid'))
  {
   $data = array(
    'sender_id'  => $this->input->post('send_userid'),
    'receiver_id' => $this->input->post('receiver_userid')
   );
   $this->chat_model->Insert_chat_request($data);
  }
 }

 function load_notification()
 {
  sleep(2);
  if($this->input->post('action'))
  {
   $data = $this->chat_model->Fetch_notification_data($this->session->userdata('user_id'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $userdata = $this->chat_model->Get_user_data($row->sender_id);

     $output[] = array(
      'user_id'  => $row->sender_id,
      'first_name' => $userdata['first_name'],
      'last_name'  => $userdata['last_name'],
      'profile_picture' => $userdata['profile_picture'],
      'chat_request_id' => $row->chat_request_id
     );
    }
   }
   echo json_encode($output);
  }
 }

 function accept_request()
 {
  if($this->input->post('chat_request_id'))
  {
   $update_data = array(
    'chat_request_status' => 'Accept'
   );
   $this->chat_model->Update_chat_request($this->input->post('chat_request_id'), $update_data);
  }
 }

 function load_chat_user()
 {
  sleep(2);
  if($this->input->post('action'))
  {
   $sender_id = $this->session->userdata('user_id');
   $receiver_id = '';
   $data = $this->chat_model->Fetch_chat_user_data($sender_id);
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     if($row->sender_id == $sender_id)
     {
      $receiver_id = $row->receiver_id;
     }
     else
     {
      $receiver_id = $row->sender_id;
     }
     $userdata = $this->chat_model->Get_user_data($receiver_id);
     $output[] = array(
      'receiver_id'  => $receiver_id,
      'first_name'  => $userdata['first_name'],
      'last_name'   => $userdata['last_name'],
      'profile_picture' => $userdata['profile_picture']
     );
    }
   }
   echo json_encode($output);
  }
 }

 function send_chat()
 {
  if($this->input->post('receiver_id'))
  {
   $data = array(
    'sender_id'  => $this->session->userdata('user_id'),
    'receiver_id' => $this->input->post('receiver_id'),
    'chat_messages_text' => $this->input->post('chat_message'),
    'chat_messages_status' => 'no',
    'chat_messages_datetime'=> date('Y-m-d H:i:s')
   );

   $this->chat_model->Insert_chat_message($data);
  }
 }

 function load_chat_data()
 {
  if($this->input->post('receiver_id'))
  {
   $receiver_id = $this->input->post('receiver_id');
   $sender_id = $this->session->userdata('user_id');
   if($this->input->post('update_data') == 'yes')
   {
    $this->chat_model->Update_chat_message_status($sender_id);
   }
   $chat_data = $this->chat_model->Fetch_chat_data($sender_id, $receiver_id);
   if($chat_data->num_rows() > 0)
   {
    foreach($chat_data->result() as $row)
    {
     $message_direction = '';
     if($row->sender_id == $sender_id)
     {
      $message_direction = 'right';
     }
     else
     {
      $message_direction = 'left';
     }
     $date = date('D M Y H:i', strtotime($row->chat_messages_datetime));
     $output[] = array(
      'chat_messages_text' => $row->chat_messages_text,
      'chat_messages_datetime'=> $date,
      'message_direction'  => $message_direction
     );
    }
   }
   echo json_encode($output);
  }
 }

 function check_chat_notification()
 {
  if($this->input->post('user_id_array'))
  {
   $receiver_id = $this->session->userdata('user_id');

   $this->chat_model->Update_login_data();

   $user_id_array = explode(",", $this->input->post('user_id_array'));

   $output = array();

   foreach($user_id_array as $sender_id)
   {
    if($sender_id != '')
    {
     $status = "offline";
     $last_activity = $this->chat_model->User_last_activity($sender_id);

     if($last_activity != '')
     {
      $current_timestamp = strtotime(date("Y-m-d H:i:s") . '- 10 second');

      $current_timestamp = date('Y-m-d H:i:s', $current_timestamp);

      if($last_activity > $current_timestamp)
      {
       $status = 'online';
      }
     }

     $output[] = array(
      'user_id'  => $sender_id,
      'total_notification' => $this->chat_model->Count_chat_notification($sender_id, $receiver_id),
      'status'  => $status
     );
    }
   }
   echo json_encode($output);
  }
 }
}
?>


Chat_model.php (Models)



<?php
class Chat_model extends CI_Model
{
 function search_user_data($user_id, $query)
 {
  $where = "user_id != '".$user_id."' AND (first_name LIKE '%".$query."%' OR last_name LIKE '%".$query."%')";

  $this->db->where($where);

  return $this->db->get('chat_user');
 }

 function Check_request_status($sender_id, $receiver_id)
 {
  $this->db->where('(sender_id = "'.$sender_id.'" OR sender_id = "'.$receiver_id.'")');
  $this->db->where('(receiver_id = "'.$receiver_id.'" OR receiver_id = "'.$sender_id.'")');
  $this->db->order_by('chat_request_id', 'DESC');
  $this->db->limit(1);
  $query = $this->db->get('chat_request');
  if($query->num_rows() > 0)
  {
   foreach($query->result() as $row)
   {
    return $row->chat_request_status;
   }
  }
 }

 function Insert_chat_request($data)
 {
  $this->db->insert('chat_request', $data);
 }

 function Fetch_notification_data($receiver_id)
 {
  $this->db->where('receiver_id', $receiver_id);
  $this->db->where('chat_request_status', 'Pending');
  return $this->db->get('chat_request');
 }

 function Get_user_data($user_id)
 {
  $this->db->where('user_id', $user_id);
  $data = $this->db->get('chat_user');
  $output = array();
  foreach($data->result() as $row)
  {
   $output['first_name'] = $row->first_name;
   $output['last_name'] = $row->last_name;
   $output['email_address'] = $row->email_address;
   $output['profile_picture'] = $row->profile_picture;
  }
  return $output;
 }

 function Update_chat_request($chat_request_id, $data)
 {
  $this->db->where('chat_request_id', $chat_request_id);
  $this->db->update('chat_request', $data);
 }

 function Fetch_chat_user_data($user_id)
 {
  $this->db->where('chat_request_status', 'Accept');
  $this->db->where('(sender_id = "'.$user_id.'" OR receiver_id = "'.$user_id.'")');
  $this->db->order_by('chat_request_id', 'DESC');
  return $this->db->get('chat_request');
 }

 function Insert_chat_message($data)
 {
  $this->db->insert('chat_messages', $data);
 }

 function Update_chat_message_status($user_id)
 {
  $data = array(
   'chat_messages_status'  => 'yes'
  );
  $this->db->where('receiver_id', $user_id);
  $this->db->where('chat_messages_status', 'no');
  $this->db->update('chat_messages', $data);
 }

 function Fetch_chat_data($sender_id, $receiver_id)
 {
  $this->db->where('(sender_id = "'.$sender_id.'" OR sender_id = "'.$receiver_id.'")');
  $this->db->where('(receiver_id = "'.$receiver_id.'" OR receiver_id = "'.$sender_id.'")');
  $this->db->order_by('chat_messages_id', 'ASC');
  return $this->db->get('chat_messages');
 }

 function Count_chat_notification($sender_id, $receiver_id)
 {
  $this->db->where('sender_id', $sender_id);
  $this->db->where('receiver_id', $receiver_id);
  $this->db->where('chat_messages_status', 'no');
  $query = $this->db->get('chat_messages');
  return $query->num_rows();
 }

 function Update_login_data()
 {
  $data = array(
   'last_activity'  => date('Y-m-d H:i:s')
  );
  $this->db->where('login_data_id', $this->session->userdata('login_id'));
  $this->db->update('login_data', $data);
 }

 function User_last_activity($user_id)
 {
  $this->db->where('user_id', $user_id);
  $this->db->order_by('login_data_id', 'DESC');
  $this->db->limit(1);
  $query = $this->db->get('login_data');
  foreach($query->result() as $row)
  {
   return $row->last_activity;
  }
 }
}
?>


chat_view.php (Views)



<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Chat Application in Codeigniter</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="<?php echo base_url(); ?>asset/js/jquery.min.js"></script>
  <script src="<?php echo base_url(); ?>asset/js/bootstrap.min.js"></script>
  <link href="<?php echo base_url(); ?>asset/css/bootstrap.min.css" rel="stylesheet" />
  <style type="text/css">
   
   #chat_message_area
   {
    width: 100%;
    height: auto;
    min-height: 80px;
    overflow: auto;
    padding:6px 24px 6px 12px;
    border: 1px solid #CCC;
       border-radius: 3px;
   }

   .notification_circle {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #FF0000;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .online
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #5cb85c;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .offline
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #ccc;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }

  </style>
 </head>
 <body>
  <div clas="container-fluid">
   <br />
   <h2 align="center"><a href="https://www.webslesson.info/2020/03/ajax-jquery-real-time-chat-application-using-codeigniter.html">Chat Application in Codeigniter</a></h2>
   <br />
   <div class="col-md-12" align="right">
    <a href="<?php echo base_url(); ?>google_login/logout">Logout</a>
   </div>
   <div class="col-md-3" style="padding-right:0;">
    <div class="panel panel-default" style="height: 700px; overflow-y: scroll;">
     <div class="panel-heading">Chat with User</div>
     <div class="panel-body" id="chat_user_area">

     </div>
     <input type="hidden" name="hidden_receiver_id_array" id="hidden_receiver_id_array" />
    </div>
   </div>
   <div class="col-md-6" style="padding-left:0; padding-right: 0;">
    <div class="panel panel-default" style="">
     <div class="panel-heading">Chat Area</div>
     <div class="panel-body">
      <div id="chat_header">
       <h2 align="center" style="margin:0; padding-bottom:16px;"><span id="dynamic_title">Welcome <?php echo $this->session->userdata('username'); ?></span></h2>
      </div>
      <div id="chat_body" style="height:406px; overflow-y: scroll;"></div>
      <div id="chat_footer" style="">
       <hr />
       <div class="form-group">
        <div id="chat_message_area" contenteditable class="form-control"></div>
       </div>
       <div class="form-group" align="right">
        <button type="button" name="send_chat" id="send_chat" class="btn btn-success btn-xs" disabled>Send</button>
       </div>
      </div>
     </div>
    </div>
   </div>
   <div class="col-md-3" style="padding-left:0;">
    <div class="panel panel-default" style="height: 300px; overflow-y: scroll;">
     <div class="panel-heading">Search User</div>
     <div class="panel-body">
      <div class="row">
       <div class="col-md-8">
        <input type="text" name="search_user" id="search_user" class="form-control input-sm" placeholder="Search User" />
       </div>
       <div class="col-md-4">
        <button type="button" name="search_button" id="search_button" class="btn btn-primary btn-sm">Search</button>
       </div>
      </div>
      
      <div id="search_user_area"></div>
      
     </div>
    </div>
    <div class="panel panel-default" style="height: 380px; overflow-y: scroll;">
     <div class="panel-heading">Nofication</div>
     <div class="panel-body" id="notification_area">
      
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script>

$(document).ready(function(){

 function loading()
 {
  var output = '<div align="center"><br /><br /><br />';
  output += '<img src="<?php echo base_url(); ?>asset/loading.gif" /> Please wait...</div>';
  return output;
 }

 $(document).on('click', '#search_button', function(){
  var search_query = $.trim($('#search_user').val());
  $('#search_user_area').html('');
  if(search_query != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>chat/search_user",
    method:"POST",
    data:{search_query:search_query},
    dataType:"json",
    beforeSend:function()
    {
     $('#search_user_area').html(loading());
     $('#search_button').attr('disabled', 'disabled');
    },
    success:function(data)
    {
     $('#search_button').attr('disabled', false);
     var output = '<hr />';
     var send_userid = "<?php echo $this->session->userdata('user_id'); ?>";
     if(data.length > 0)
     {
      for(var count = 0; count < data.length; count++)
      {
       output += '<div class="row">';
       output += '<div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="40" /> <small>'+data[count].first_name+' '+data[count].last_name+'</small></div>';
       if(data[count].is_request_send == 'yes')
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-warning btn-xs">Request Sended</button></div>';
       }
       else
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-success btn-xs request_button" id="request_button'+data[count].user_id+'" data-receiver_userid="'+data[count].user_id+'" data-send_userid="'+send_userid+'">Send Request</button></div>';
       }
       output += '</div><hr />';
      }
     }
     else
     {
      output += '<div align="center"><b>No Data Found</b></div>';
     }
     output += '</div>';
     $('#search_user_area').html(output);
    }
   })
  }
 });

 $(document).on('click', '.request_button', function(){
  var id = $(this).attr('id');
  var receiver_userid = $(this).data('receiver_userid');
  var send_userid = $(this).data('send_userid');
  $.ajax({
   url:"<?php echo base_url(); ?>chat/send_request",
   method:"POST",
   data:{receiver_userid:receiver_userid, send_userid:send_userid},
   beforeSend:function()
   {
    $('#'+id).attr('disabled', 'disabled');
   },
   success:function(data)
   {
    $('#'+id).attr('disabled', false);
    $('#'+id).removeClass('btn-success');
    $('#'+id).addClass('btn-warning');
    $('#'+id).text('Request Sended');
   }
  })
 })

 load_notification();

 function load_notification()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_notification",
   method:"POST",
   data:{action:'load_notification'},
   dataType:"json",
   beforeSend:function()
   {
    $('#notification_area').html(loading());
   },
   success:function(data)
   {
    var output = '<hr />';
    //console.log(data.length);
    if(data.length > 0)
    {
     for(var count = 0; count < data.length; count++)
     {
      output += '<div class="row"><div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="35" /> ' + data[count].first_name + ' ' +data[count].last_name + '</div>';

      output += '<div class="col-md-5"><button type="button" name="accept_button" class="btn btn-success btn-xs accept_button" id="accept_button'+data[count].user_id+'" data-chat_request_id="'+data[count].chat_request_id+'">Accept</button></div><hr />';
     }
    }
    else
    {
     output += '<div align="center"><b>No Data Found</b></div>';
    }
    //output += '</div><hr />';
    $('#notification_area').html(output);
   }
  }) 
 }

 $(document).on('click', '.accept_button', function(){
  var id = $(this).attr('id');
  var chat_request_id = $(this).data('chat_request_id');
  $.ajax({
   url:"<?php echo base_url(); ?>chat/accept_request",
   method:"POST",
   data:{chat_request_id:chat_request_id},
   beforeSend:function()
   {
    $('#'+id).attr('disabled','disabled');
   },
   success:function(data)
   {
    $('#'+id).attr('disabled', false);
    $('#'+id).removeClass('btn-success');
    $('#'+id).addClass('btn-warning');
    $('#'+id).text('Accepted');
   }
  })
 });

 load_chat_user();

 function load_chat_user()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_chat_user",
   method:"POST",
   data:{action:'load_chat_user'},
   dataType:'json',
   beforeSend:function()
   {
    $('#chat_user_area').html(loading());
   },
   success:function(data)
   {
    var output = '<div class="list-group">';
    if(data.length > 0)
    {
     var receiver_id_array = '';
     for(var count = 0; count < data.length; count++)
     {
      output += '<a href="javascript:void(0)" class="list-group-item user_chat_list" data-receiver_id="'+data[count].receiver_id+'">';

      output += '<img src="'+data[count].profile_picture+'" class="img-circle" width="35" />';

      output += ' ' + data[count].first_name + ' ' + data[count].last_name;

      output += '&nbsp;<span id="chat_notification_'+data[count].receiver_id + '"></span>';

      output += ' <i class="offline" id="online_status_'+data[count].receiver_id+'" style="float:right;">&nbsp;</i></a>';

      receiver_id_array += data[count].receiver_id + ',';
     }
     $('#hidden_receiver_id_array').val(receiver_id_array);
    }
    else
    {
     output += '<div align="center"><b>No Data Found</b></div>';
    }
    output += '</div>';
    $('#chat_user_area').html(output);
   }
  })
 }

 var receiver_id;

 $(document).on('click', '.user_chat_list', function(){
  $('#send_chat').attr('disabled', false);
  receiver_id = $(this).data('receiver_id');
  var receiver_name = $(this).text();
  $('#dynamic_title').text('You Chat with ' + receiver_name);
  load_chat_data(receiver_id, 'yes');
 });

 $(document).on('click', '#send_chat', function(){
  var chat_message = $.trim($('#chat_message_area').html());
  if(chat_message != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>chat/send_chat",
    method:"POST",
    data:{receiver_id:receiver_id, chat_message:chat_message},
    beforeSend:function()
    {
     $('#send_chat').attr('disabled','disabled');
    },
    success:function(data)
    {
     $('#send_chat').attr('disabled', false);
     $('#chat_message_area').html('');
     var html = '<div class="col-md-10 alert alert-warning">';
     html += chat_message;
     html += '</div>';
     $('#chat_body').append(html);
     $('#chat_body').scrollTop($('#chat_body')[0].scrollHeight);
    }
   });
  }
  else
  {
   alert('Type Something in chat box');
  }
 });

 function load_chat_data(receiver_id, update_data)
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_chat_data",
   method:"POST",
   data:{receiver_id:receiver_id, update_data:update_data},
   dataType:"json",
   success:function(data)
   {
    var html = '';
    for(var count = 0; count < data.length; count++)
    {
     html += '<div class="row" style="margin-left:0; margin-right:0">';
     if(data[count].message_direction == 'right')
     {
      html += '<div align="left"><span class="text-muted"><small><b>'+data[count].chat_messages_datetime+'</b></small></span></div>';

      html += '<div class="col-md-10 alert alert-warning">';
     }
     else
     {
      html += '<div align="right"><span class="text-muted"><small><b>'+data[count].chat_messages_datetime+'</b></small></span></div>';
      html += '<div class="col-md-2">&nbsp;</div>';
      html += '<div class="col-md-10 alert alert-info">';
     }
     html += data[count].chat_messages_text + '</div></div>';
    }
    $('#chat_body').html(html);
    $('#chat_body').scrollTop($('#chat_body')[0].scrollHeight);
   }
  })
 }

 setInterval(function(){
  if(receiver_id > 0)
  {
   load_chat_data(receiver_id, 'yes');
  }
  check_chat_notification();
 }, 5000);

 function check_chat_notification()
 {
  var user_id_array = $('#hidden_receiver_id_array').val();
  $.ajax({
   url:"<?php echo base_url(); ?>chat/check_chat_notification",
   method:"POST",
   data:{user_id_array:user_id_array, is_type:is_type, receiver_id:receiver_id},
   dataType:"json",
   success:function(data)
   {
    if(data.length > 0)
    {
     for(var count = 0; count < data.length; count++)
     {
      var html = '';
      if(data[count].total_notification > 0)
      {
       if(data[count].user_id != receiver_id)
       {
        html = '<span class="notification_circle">'+data[count].total_notification+'</span>';
       }
      }
      console.log(data[count].status);

      if(data[count].status == 'online')
      {
       console.log('online_status_'+data[count].user_id);
       $('#online_status_'+data[count].user_id).addClass('online');
       $('#online_status_'+data[count].user_id).removeClass('offline');
      }
      else
      {
       $('#online_status_'+data[count].user_id).addClass('offline');

       $('#online_status_'+data[count].user_id).removeClass('online');
      }

      $('#chat_notification_'+data[count].user_id).html(html);
     }
    }
   }
  })
 }

});

</script>


Display User is Typing


In this section, we have add one more feature in this Chat application. Here we have add WhatsApp like display typing text at below user name. When one user has type then another user can know that user is typing something in his or her chat box. So, this type of feature we have add in this Codeigniter chat application by using Ajax jquery. For this User is typing or not feature, we have made following changes in Codeigniter Controllers, Models and View files.


Chat.php (Controllers)



<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Chat extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('chat_model');
  date_default_timezone_set("Asia/Calcutta");
  if(!$this->session->userdata('user_id'))
  {
   redirect('google_login/login');
  }
 }

 function index()
 {
  $this->load->view('chat_view');
 }

 function search_user()
 {
  sleep(2);
  if($this->input->post('search_query'))
  {
   $data = $this->chat_model->search_user_data($this->session->userdata('user_id'), $this->input->post('search_query'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $request_status = $this->chat_model->Check_request_status($this->session->userdata('user_id'), $row->user_id);
     $is_request_send = 'yes';
     if($request_status == '')
     {
      $is_request_send = 'no';
     } 
     else
     {
      if($request_status == 'pending')
      {
       $is_request_send = 'yes';
      }
     }
     if($request_status != 'Accept')
     {
      $output[] = array(
       'user_id'  => $row->user_id,
       'first_name' => $row->first_name,
       'last_name'  => $row->last_name,
       'profile_picture'=> $row->profile_picture,
       'is_request_send'=> $is_request_send
      );
     } 
    }
   }
   echo json_encode($output);
  }
 }

 function send_request()
 {
  sleep(2);
  if($this->input->post('send_userid'))
  {
   $data = array(
    'sender_id'  => $this->input->post('send_userid'),
    'receiver_id' => $this->input->post('receiver_userid')
   );
   $this->chat_model->Insert_chat_request($data);
  }
 }

 function load_notification()
 {
  sleep(2);
  if($this->input->post('action'))
  {
   $data = $this->chat_model->Fetch_notification_data($this->session->userdata('user_id'));
   $output = array();
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     $userdata = $this->chat_model->Get_user_data($row->sender_id);

     $output[] = array(
      'user_id'  => $row->sender_id,
      'first_name' => $userdata['first_name'],
      'last_name'  => $userdata['last_name'],
      'profile_picture' => $userdata['profile_picture'],
      'chat_request_id' => $row->chat_request_id
     );
    }
   }
   echo json_encode($output);
  }
 }

 function accept_request()
 {
  if($this->input->post('chat_request_id'))
  {
   $update_data = array(
    'chat_request_status' => 'Accept'
   );
   $this->chat_model->Update_chat_request($this->input->post('chat_request_id'), $update_data);
  }
 }

 function load_chat_user()
 {
  sleep(2);
  if($this->input->post('action'))
  {
   $sender_id = $this->session->userdata('user_id');
   $receiver_id = '';
   $data = $this->chat_model->Fetch_chat_user_data($sender_id);
   if($data->num_rows() > 0)
   {
    foreach($data->result() as $row)
    {
     if($row->sender_id == $sender_id)
     {
      $receiver_id = $row->receiver_id;
     }
     else
     {
      $receiver_id = $row->sender_id;
     }
     $userdata = $this->chat_model->Get_user_data($receiver_id);
     $output[] = array(
      'receiver_id'  => $receiver_id,
      'first_name'  => $userdata['first_name'],
      'last_name'   => $userdata['last_name'],
      'profile_picture' => $userdata['profile_picture']
     );
    }
   }
   echo json_encode($output);
  }
 }

 function send_chat()
 {
  if($this->input->post('receiver_id'))
  {
   $data = array(
    'sender_id'  => $this->session->userdata('user_id'),
    'receiver_id' => $this->input->post('receiver_id'),
    'chat_messages_text' => $this->input->post('chat_message'),
    'chat_messages_status' => 'no',
    'chat_messages_datetime'=> date('Y-m-d H:i:s')
   );

   $this->chat_model->Insert_chat_message($data);
  }
 }

 function load_chat_data()
 {
  if($this->input->post('receiver_id'))
  {
   $receiver_id = $this->input->post('receiver_id');
   $sender_id = $this->session->userdata('user_id');
   if($this->input->post('update_data') == 'yes')
   {
    $this->chat_model->Update_chat_message_status($sender_id);
   }
   $chat_data = $this->chat_model->Fetch_chat_data($sender_id, $receiver_id);
   if($chat_data->num_rows() > 0)
   {
    foreach($chat_data->result() as $row)
    {
     $message_direction = '';
     if($row->sender_id == $sender_id)
     {
      $message_direction = 'right';
     }
     else
     {
      $message_direction = 'left';
     }
     $date = date('D M Y H:i', strtotime($row->chat_messages_datetime));
     $output[] = array(
      'chat_messages_text' => $row->chat_messages_text,
      'chat_messages_datetime'=> $date,
      'message_direction'  => $message_direction
     );
    }
   }
   echo json_encode($output);
  }
 }

 function check_chat_notification()
 {
  if($this->input->post('user_id_array'))
  {
   $receiver_id = $this->session->userdata('user_id');

   $this->chat_model->Update_login_data();

   $user_id_array = explode(",", $this->input->post('user_id_array'));

   $output = array();

   foreach($user_id_array as $sender_id)
   {
    if($sender_id != '')
    {
     $status = "offline";
     $last_activity = $this->chat_model->User_last_activity($sender_id);

     $is_type = '';

     if($last_activity != '')
     {
      $current_timestamp = strtotime(date("Y-m-d H:i:s") . '- 10 second');

      $current_timestamp = date('Y-m-d H:i:s', $current_timestamp);

      if($last_activity > $current_timestamp)
      {
       $status = 'online';
       $is_type = $this->chat_model->Check_type_notification($sender_id, $receiver_id, $current_timestamp);
      }
     }

     $output[] = array(
      'user_id'  => $sender_id,
      'total_notification' => $this->chat_model->Count_chat_notification($sender_id, $receiver_id),
      'status'  => $status,
      'is_type'  => $is_type
     );
    }
   }
   echo json_encode($output);
  }
 }
}
?>


Chat_model.php (Models)



<?php
class Chat_model extends CI_Model
{
 function search_user_data($user_id, $query)
 {
  $where = "user_id != '".$user_id."' AND (first_name LIKE '%".$query."%' OR last_name LIKE '%".$query."%')";

  $this->db->where($where);

  return $this->db->get('chat_user');
 }

 function Check_request_status($sender_id, $receiver_id)
 {
  $this->db->where('(sender_id = "'.$sender_id.'" OR sender_id = "'.$receiver_id.'")');
  $this->db->where('(receiver_id = "'.$receiver_id.'" OR receiver_id = "'.$sender_id.'")');
  $this->db->order_by('chat_request_id', 'DESC');
  $this->db->limit(1);
  $query = $this->db->get('chat_request');
  if($query->num_rows() > 0)
  {
   foreach($query->result() as $row)
   {
    return $row->chat_request_status;
   }
  }
 }

 function Insert_chat_request($data)
 {
  $this->db->insert('chat_request', $data);
 }

 function Fetch_notification_data($receiver_id)
 {
  $this->db->where('receiver_id', $receiver_id);
  $this->db->where('chat_request_status', 'Pending');
  return $this->db->get('chat_request');
 }

 function Get_user_data($user_id)
 {
  $this->db->where('user_id', $user_id);
  $data = $this->db->get('chat_user');
  $output = array();
  foreach($data->result() as $row)
  {
   $output['first_name'] = $row->first_name;
   $output['last_name'] = $row->last_name;
   $output['email_address'] = $row->email_address;
   $output['profile_picture'] = $row->profile_picture;
  }
  return $output;
 }

 function Update_chat_request($chat_request_id, $data)
 {
  $this->db->where('chat_request_id', $chat_request_id);
  $this->db->update('chat_request', $data);
 }

 function Fetch_chat_user_data($user_id)
 {
  $this->db->where('chat_request_status', 'Accept');
  $this->db->where('(sender_id = "'.$user_id.'" OR receiver_id = "'.$user_id.'")');
  $this->db->order_by('chat_request_id', 'DESC');
  return $this->db->get('chat_request');
 }

 function Insert_chat_message($data)
 {
  $this->db->insert('chat_messages', $data);
 }

 function Update_chat_message_status($user_id)
 {
  $data = array(
   'chat_messages_status'  => 'yes'
  );
  $this->db->where('receiver_id', $user_id);
  $this->db->where('chat_messages_status', 'no');
  $this->db->update('chat_messages', $data);
 }

 function Fetch_chat_data($sender_id, $receiver_id)
 {
  $this->db->where('(sender_id = "'.$sender_id.'" OR sender_id = "'.$receiver_id.'")');
  $this->db->where('(receiver_id = "'.$receiver_id.'" OR receiver_id = "'.$sender_id.'")');
  $this->db->order_by('chat_messages_id', 'ASC');
  return $this->db->get('chat_messages');
 }

 function Count_chat_notification($sender_id, $receiver_id)
 {
  $this->db->where('sender_id', $sender_id);
  $this->db->where('receiver_id', $receiver_id);
  $this->db->where('chat_messages_status', 'no');
  $query = $this->db->get('chat_messages');
  return $query->num_rows();
 }

 function Update_login_data()
 {
  $data = array(
   'last_activity'  => date('Y-m-d H:i:s'),
   'is_type'   => $this->input->post('is_type'),
   'receiver_user_id' => $this->input->post('receiver_id')
  );
  $this->db->where('login_data_id', $this->session->userdata('login_id'));
  $this->db->update('login_data', $data);
 }

 function User_last_activity($user_id)
 {
  $this->db->where('user_id', $user_id);
  $this->db->order_by('login_data_id', 'DESC');
  $this->db->limit(1);
  $query = $this->db->get('login_data');
  foreach($query->result() as $row)
  {
   return $row->last_activity;
  }
 }

 function Check_type_notification($sender_id, $receiver_id, $current_timestamp)
 {
  $this->db->where('receiver_user_id', $receiver_id);
  $this->db->where('user_id', $sender_id);
  $this->db->where('last_activity >', $current_timestamp);
  $this->db->order_by('login_data_id', 'DESC');
  $this->db->limit(1);
  $query = $this->db->get('login_data');
  foreach($query->result() as $row)
  {
   return $row->is_type;
  }
 }
}
?>


chat_view.php (Views)



<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Chat Application in Codeigniter</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="<?php echo base_url(); ?>asset/js/jquery.min.js"></script>
  <script src="<?php echo base_url(); ?>asset/js/bootstrap.min.js"></script>
  <link href="<?php echo base_url(); ?>asset/css/bootstrap.min.css" rel="stylesheet" />
  <style type="text/css">
   
   #chat_message_area
   {
    width: 100%;
    height: auto;
    min-height: 80px;
    overflow: auto;
    padding:6px 24px 6px 12px;
    border: 1px solid #CCC;
       border-radius: 3px;
   }

   .notification_circle {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #FF0000;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .online
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #5cb85c;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }
   .offline
   {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #ccc;
    text-align: center;
    color:#fff;
    padding:3px 6px;
   }

  </style>
 </head>
 <body>
  <div clas="container-fluid">
   <br />
   <h2 align="center"><a href="https://www.webslesson.info/2020/03/ajax-jquery-real-time-chat-application-using-codeigniter.html">Chat Application in Codeigniter</a></h2>
   <br />
   <div class="col-md-12" align="right">
    <a href="<?php echo base_url(); ?>google_login/logout">Logout</a>
   </div>
   <div class="col-md-3" style="padding-right:0;">
    <div class="panel panel-default" style="height: 700px; overflow-y: scroll;">
     <div class="panel-heading">Chat with User</div>
     <div class="panel-body" id="chat_user_area">

     </div>
     <input type="hidden" name="hidden_receiver_id_array" id="hidden_receiver_id_array" />
    </div>
   </div>
   <div class="col-md-6" style="padding-left:0; padding-right: 0;">
    <div class="panel panel-default" style="">
     <div class="panel-heading">Chat Area</div>
     <div class="panel-body">
      <div id="chat_header">
       <h2 align="center" style="margin:0; padding-bottom:16px;"><span id="dynamic_title">Welcome <?php echo $this->session->userdata('username'); ?></span></h2>
      </div>
      <div id="chat_body" style="height:406px; overflow-y: scroll;"></div>
      <div id="chat_footer" style="">
       <hr />
       <div class="form-group">
        <div id="chat_message_area" contenteditable class="form-control"></div>
       </div>
       <div class="form-group" align="right">
        <button type="button" name="send_chat" id="send_chat" class="btn btn-success btn-xs" disabled>Send</button>
       </div>
      </div>
     </div>
    </div>
   </div>
   <div class="col-md-3" style="padding-left:0;">
    <div class="panel panel-default" style="height: 300px; overflow-y: scroll;">
     <div class="panel-heading">Search User</div>
     <div class="panel-body">
      <div class="row">
       <div class="col-md-8">
        <input type="text" name="search_user" id="search_user" class="form-control input-sm" placeholder="Search User" />
       </div>
       <div class="col-md-4">
        <button type="button" name="search_button" id="search_button" class="btn btn-primary btn-sm">Search</button>
       </div>
      </div>
      
      <div id="search_user_area"></div>
      
     </div>
    </div>
    <div class="panel panel-default" style="height: 380px; overflow-y: scroll;">
     <div class="panel-heading">Nofication</div>
     <div class="panel-body" id="notification_area">
      
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script>

$(document).ready(function(){

 function loading()
 {
  var output = '<div align="center"><br /><br /><br />';
  output += '<img src="<?php echo base_url(); ?>asset/loading.gif" /> Please wait...</div>';
  return output;
 }

 $(document).on('click', '#search_button', function(){
  var search_query = $.trim($('#search_user').val());
  $('#search_user_area').html('');
  if(search_query != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>chat/search_user",
    method:"POST",
    data:{search_query:search_query},
    dataType:"json",
    beforeSend:function()
    {
     $('#search_user_area').html(loading());
     $('#search_button').attr('disabled', 'disabled');
    },
    success:function(data)
    {
     $('#search_button').attr('disabled', false);
     var output = '<hr />';
     var send_userid = "<?php echo $this->session->userdata('user_id'); ?>";
     if(data.length > 0)
     {
      for(var count = 0; count < data.length; count++)
      {
       output += '<div class="row">';
       output += '<div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="40" /> <small>'+data[count].first_name+' '+data[count].last_name+'</small></div>';
       if(data[count].is_request_send == 'yes')
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-warning btn-xs">Request Sended</button></div>';
       }
       else
       {
        output += '<div class="col-md-5"><button type="button" name="request_button" class="btn btn-success btn-xs request_button" id="request_button'+data[count].user_id+'" data-receiver_userid="'+data[count].user_id+'" data-send_userid="'+send_userid+'">Send Request</button></div>';
       }
       output += '</div><hr />';
      }
     }
     else
     {
      output += '<div align="center"><b>No Data Found</b></div>';
     }
     output += '</div>';
     $('#search_user_area').html(output);
    }
   })
  }
 });

 $(document).on('click', '.request_button', function(){
  var id = $(this).attr('id');
  var receiver_userid = $(this).data('receiver_userid');
  var send_userid = $(this).data('send_userid');
  $.ajax({
   url:"<?php echo base_url(); ?>chat/send_request",
   method:"POST",
   data:{receiver_userid:receiver_userid, send_userid:send_userid},
   beforeSend:function()
   {
    $('#'+id).attr('disabled', 'disabled');
   },
   success:function(data)
   {
    $('#'+id).attr('disabled', false);
    $('#'+id).removeClass('btn-success');
    $('#'+id).addClass('btn-warning');
    $('#'+id).text('Request Sended');
   }
  })
 })

 load_notification();

 function load_notification()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_notification",
   method:"POST",
   data:{action:'load_notification'},
   dataType:"json",
   beforeSend:function()
   {
    $('#notification_area').html(loading());
   },
   success:function(data)
   {
    var output = '<hr />';
    //console.log(data.length);
    if(data.length > 0)
    {
     for(var count = 0; count < data.length; count++)
     {
      output += '<div class="row"><div class="col-md-7"><img src="'+data[count].profile_picture+'" class="img-circle" width="35" /> ' + data[count].first_name + ' ' +data[count].last_name + '</div>';

      output += '<div class="col-md-5"><button type="button" name="accept_button" class="btn btn-success btn-xs accept_button" id="accept_button'+data[count].user_id+'" data-chat_request_id="'+data[count].chat_request_id+'">Accept</button></div><hr />';
     }
    }
    else
    {
     output += '<div align="center"><b>No Data Found</b></div>';
    }
    //output += '</div><hr />';
    $('#notification_area').html(output);
   }
  }) 
 }

 $(document).on('click', '.accept_button', function(){
  var id = $(this).attr('id');
  var chat_request_id = $(this).data('chat_request_id');
  $.ajax({
   url:"<?php echo base_url(); ?>chat/accept_request",
   method:"POST",
   data:{chat_request_id:chat_request_id},
   beforeSend:function()
   {
    $('#'+id).attr('disabled','disabled');
   },
   success:function(data)
   {
    $('#'+id).attr('disabled', false);
    $('#'+id).removeClass('btn-success');
    $('#'+id).addClass('btn-warning');
    $('#'+id).text('Accepted');
   }
  })
 });

 load_chat_user();

 function load_chat_user()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_chat_user",
   method:"POST",
   data:{action:'load_chat_user'},
   dataType:'json',
   beforeSend:function()
   {
    $('#chat_user_area').html(loading());
   },
   success:function(data)
   {
    var output = '<div class="list-group">';
    if(data.length > 0)
    {
     var receiver_id_array = '';
     for(var count = 0; count < data.length; count++)
     {
      output += '<a href="javascript:void(0)" class="list-group-item user_chat_list" data-receiver_id="'+data[count].receiver_id+'">';

      output += '<img src="'+data[count].profile_picture+'" class="img-circle" width="35" />';

      output += ' ' + data[count].first_name + ' ' + data[count].last_name;

      output += '&nbsp;<span id="chat_notification_'+data[count].receiver_id + '"></span>';
      ///
      output += '&nbsp;<span id="type_notifitcation_'+data[count].receiver_id+'"></span>';
      
      ///

      output += ' <i class="offline" id="online_status_'+data[count].receiver_id+'" style="float:right;">&nbsp;</i></a>';

      receiver_id_array += data[count].receiver_id + ',';
     }
     $('#hidden_receiver_id_array').val(receiver_id_array);
    }
    else
    {
     output += '<div align="center"><b>No Data Found</b></div>';
    }
    output += '</div>';
    $('#chat_user_area').html(output);
   }
  })
 }

 var receiver_id;

 $(document).on('click', '.user_chat_list', function(){
  $('#send_chat').attr('disabled', false);
  receiver_id = $(this).data('receiver_id');
  var receiver_name = $(this).text();
  $('#dynamic_title').text('You Chat with ' + receiver_name);
  load_chat_data(receiver_id, 'yes');
 });

 $(document).on('click', '#send_chat', function(){
  var chat_message = $.trim($('#chat_message_area').html());
  if(chat_message != '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>chat/send_chat",
    method:"POST",
    data:{receiver_id:receiver_id, chat_message:chat_message},
    beforeSend:function()
    {
     $('#send_chat').attr('disabled','disabled');
    },
    success:function(data)
    {
     $('#send_chat').attr('disabled', false);
     $('#chat_message_area').html('');
     var html = '<div class="col-md-10 alert alert-warning">';
     html += chat_message;
     html += '</div>';
     $('#chat_body').append(html);
     $('#chat_body').scrollTop($('#chat_body')[0].scrollHeight);
    }
   });
  }
  else
  {
   alert('Type Something in chat box');
  }
 });

 function load_chat_data(receiver_id, update_data)
 {
  $.ajax({
   url:"<?php echo base_url(); ?>chat/load_chat_data",
   method:"POST",
   data:{receiver_id:receiver_id, update_data:update_data},
   dataType:"json",
   success:function(data)
   {
    var html = '';
    for(var count = 0; count < data.length; count++)
    {
     html += '<div class="row" style="margin-left:0; margin-right:0">';
     if(data[count].message_direction == 'right')
     {
      html += '<div align="left"><span class="text-muted"><small><b>'+data[count].chat_messages_datetime+'</b></small></span></div>';

      html += '<div class="col-md-10 alert alert-warning">';
     }
     else
     {
      html += '<div align="right"><span class="text-muted"><small><b>'+data[count].chat_messages_datetime+'</b></small></span></div>';
      html += '<div class="col-md-2">&nbsp;</div>';
      html += '<div class="col-md-10 alert alert-info">';
     }
     html += data[count].chat_messages_text + '</div></div>';
    }
    $('#chat_body').html(html);
    $('#chat_body').scrollTop($('#chat_body')[0].scrollHeight);
   }
  })
 }

 setInterval(function(){
  if(receiver_id > 0)
  {
   load_chat_data(receiver_id, 'yes');
  }
  check_chat_notification(receiver_id);
 }, 5000);

 function check_chat_notification(receiver_id)
 {
  var user_id_array = $('#hidden_receiver_id_array').val();

  ///
  var is_type = 'no';
  if(receiver_id > 0)
  {
   if($.trim($('#chat_message_area').text()) != '')
   {
    is_type = 'yes';
   }
  }
  ///

  $.ajax({
   url:"<?php echo base_url(); ?>chat/check_chat_notification",
   method:"POST",
   data:{user_id_array:user_id_array, is_type:is_type, receiver_id:receiver_id},
   dataType:"json",
   success:function(data)
   {
    if(data.length > 0)
    {
     for(var count = 0; count < data.length; count++)
     {
      var html = '';
      if(data[count].total_notification > 0)
      {
       if(data[count].user_id != receiver_id)
       {
        html = '<span class="notification_circle">'+data[count].total_notification+'</span>';
       }
      }
      console.log(data[count].status);

      if(data[count].status == 'online')
      {
       console.log('online_status_'+data[count].user_id);
       $('#online_status_'+data[count].user_id).addClass('online');
       $('#online_status_'+data[count].user_id).removeClass('offline');
       //
       if(data[count].is_type == 'yes')
       {
        $('#type_notifitcation_'+data[count].user_id).html('<i><small>Typing</small></i>');
       }
       else
       {
        $('#type_notifitcation_'+data[count].user_id).html('');
       }
      }
      else
      {
       $('#online_status_'+data[count].user_id).addClass('offline');

       $('#online_status_'+data[count].user_id).removeClass('online');

       //
       $('#type_notifitcation_'+data[count].user_id).html('');
      }

      $('#chat_notification_'+data[count].user_id).html(html);
     }
    }
   }
  })
 }

});

</script>


Remaining Source code will be added very soon.

15 comments:

  1. this is very wonderful project sir

    ReplyDelete
  2. thank you very much for a good job you are doing. We are awaiting the rest of this application.

    ReplyDelete
  3. Sir , please upload Source code in zip file

    ReplyDelete
  4. can you pls give us the script for download?

    ReplyDelete
  5. how to remove password hashing so that i can see my password in database.

    ReplyDelete
  6. very awesome tutorial, i hope you makes more video

    ReplyDelete
  7. hello sir code are not working. plz add source code

    ReplyDelete
  8. hello sir code are not working. plz add source code

    ReplyDelete
  9. This is good ... I'll be waiting for the remaining source code...

    ReplyDelete
  10. i think this is not working properly

    ReplyDelete
  11. how i dowload google login libaray

    ReplyDelete