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 can Accept Chat Request
  • Load Accepted Chat User
  • Send Chat Messages
  • Load Chat Messages
  • Display Unread Messsage Notification
  • Chat User Online or Offline Status




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
) 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>


Remaining Source code will be added very soon.

Saturday, 21 March 2020

Google Login Integration in Codeigniter



If you are looking for tutorial on How to Create Login by using Google Account with Codeigniter framework, then you land on right page, because in this post we have describe step by step process for integrate Google Account login in Codeigniter framework.

Currently, most of the website has provide feature like Login into their website by using Google Account. By using Google Login account user can directly login into website without register into that website, and user can directly enter website without registration.

Now in your mind one question will aris, how can we use Google Account for login into website. So for this Google has provide api for use Google account for login into website. Google has provide OAuth 2.0 API, which is open authentication api and it is very powerful for authenticate user login. By using this API, we can access user data from server and acter authenticate user data via Google account, user can get access into website.





So, In this tutorial, we will learn How can we integrate Google Open authentication login into Codeigniter website. Below you can find step by step process for integration of Login using Google Account in Codeigniter Framework.

  1. Create Google API Credential
  2. Download Google API php client library
  3. Define Autoload library
  4. Define Base Url of Codeigniter Application
  5. Make Database connection
  6. Create Controller
  7. Create Model
  8. Create View file


Create Google API Credential


For get Google API Credential, we need Google Account, if you have Google Account then you to first login into you account.

1 - If you are login into Google account, then you have to https://console.developers.google.com/ url.

2 - Once you have open above link, then first you have to create new project by click on create project link.




3 - After click on project link then new page will open, and here we have enter project name and click on create button.




4 - Next you can see newly created project on web page. And after this we have to click on OAuth consent screen link.






5 - After click on OAuth consent screen, then after new page has been load in browser, and here we can see two User Type option, and from that option we have to select External and click on Create button.




6 - Once we have click on Create button, then web page has redirect to new page, and on this page, we have to define Application Name and after this click on Save button.




7 - When we have click on Save button, then web page has redirect to this page. Here we can see our application details. Next we have to click on Credentials link at the left side menu.




8 - After click on Credentials link, then Credentials web page has been load in browser. And here we have to click on CREATE CREDENTIALS button.




9 - Once we have click on CREATE CREDENTIALS button, then one dropdown has been appear on web page with four option. And from that option, we have to select OAuth client ID link.




10 - When we have click on OAuth client ID option, then one new page has been load in browser and here we have to define Application Type from different option. So, from that option, we have to select Web Application.




11 - Once we have select Web Application, then below that field new field has been appear and in that field, we have to enter Name field details and define Authorized redirect Uris. This is for use with request from server, and lastly we have to click on Create button.




12 - Once we have click on Create button, then our Application has been register, and then after new page has been load with our application Client ID and Client secret key will appear on web page. We have to use both key in Codeigniter framework for make Login using Google Account.




2 - Download Google API php client library


Once we have get Google Client ID and Client Secret key, so next we have to download Google API Client Library for PHP script. So for this, first we have go to command prompt in which we have already install Composer command, and after this we have go to library folder of codeigniter framework in which we have to download library and run following command.


composer require google/apiclient:"^2.0"


This command will download Google API Client Library for PHP language in your define directory. Next we have proceed for write code in Codeigniter framework.

3 - Define Autoload library


In Codeigniter framework, we have to first define autoload library like database and session, so once we have define library, then we have do not want to again and again load in every method. For this we have to open application/config/autoload.php file.


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


4 - Define Base Url of Codeigniter Application


In Next step we have to define base url of your Codeigniter application. This is root url of you codeigniter application. For define Base url, we have to open application/config/config.php and write base url of your application.


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






5 - Make Database connection


Once we have define base url, next we want to make Msyql database connection. For this we have to open application/config/database.php and in that file we have to define 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
);


6 - Create Controller


In Codeigniter framework, controller is used for handle http request. In Codeigniter framework controller class file has been store under application/controllers folder Here we have create controller with Google_login.php file name. In this controller here we have make following method.

__construct() - This is magic function code will be executed every time, when object of this class has been created.

login() - This method will communicate with Google Login Api by using Google API client library for PHP script. In this method we to set ClientID, ClientSecret key and Redirect Uri which we have to define at the time creating credential process. Once this all has been set then we can send login request to Google server, then from server this method will received access token and based on that token user can login into website and get user data. If user data already store in our database, then this function will update data, otherwise it will insert user data in our database.

logout() - This method will received request from user to get permission for logout from system. In this method it has simply delete data from session variable and it will redirect page to login.

application/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 login()
 {
  include_once APPPATH . "libraries/vendor/autoload.php";

  $google_client = new Google_Client();

  $google_client->setClientId(''); //Define your ClientID

  $google_client->setClientSecret(''); //Define your Client Secret Key

  $google_client->setRedirectUri(''); //Define your Redirect Uri

  $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(
      '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);
   }
  }
  $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', $data);
  }
 }

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

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

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


7 - Create Model


Model class generally used for database related operation. In codeigniter framework, Model class has been store under application/models folder. Here we have create Models class with Google_login_model.php file. In this class we have make following method.

Is_already_register($id) - This method has been check user with $id variable value is already store in chat_user table or not. If user data is available then it will return true, otherwise it will return false.

Update_user_data($data, $id) - This method will update chat_user table data based on value of $id variable value.

Insert_user_data($data) - This method will insert data into chat_user table.

application/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);
 }
}
?>





8 - Create View file


This file is used for display html output in browser. In Codeigniter framework view file has been store in application/views folder. Here we have create views file with google_login.php name.

application/views/google_login.php

<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Login with Google 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" />
  
 </head>
 <body>
  <div class="container">
   <br />
   <h2 align="center">Login using Google Account with Codeigniter</h2>
   <br />
   <div class="panel panel-default">
   <?php
   if(!isset($login_button))
   {

    $user_data = $this->session->userdata('user_data');
    echo '<div class="panel-heading">Welcome User</div><div class="panel-body">';
    echo '<img src="'.$user_data['profile_picture'].'" class="img-responsive img-circle img-thumbnail" />';
    echo '<h3><b>Name : </b>'.$user_data["first_name"].' '.$user_data['last_name']. '</h3>';
    echo '<h3><b>Email :</b> '.$user_data['email_address'].'</h3>';
    echo '<h3><a href="'.base_url().'google_login/logout">Logout</h3></div>';
   }
   else
   {
    echo '<div align="center">'.$login_button . '</div>';
   }
   ?>
   </div>
  </div>
 </body>
</html>


So, this is complete step by step process for How to implement Codeigniter Login application by using Google Account. If you have still not understand code, then you can also view video tutorial of this post also which you can find at the top of this post.