Showing posts with label json. Show all posts
Showing posts with label json. Show all posts

Tuesday, 14 March 2023

Ajax Live Search using Node.js with MySQL


In today's fast-paced world, users expect web applications to be responsive and efficient. One of the ways to achieve this is by implementing an Ajax live search feature on your website. This feature allows users to search for content on your website without having to reload the page. In this article, we will show you how to implement an Ajax live search feature using Node.js and MySQL.

Node.js is an open-source, cross-platform JavaScript runtime environment that allows developers to build server-side applications with JavaScript. MySQL is a popular open-source relational database management system that is widely used in web development. Together, they provide a powerful combination for building web applications.

To get started, you will need to have Node.js and MySQL installed on your machine. You will also need to have a basic understanding of JavaScript, HTML, and CSS.


Ajax Live Search using Node.js with MySQL


Step 1: Setting up the Database


The first step is to set up the database. You will need to create a table to store the data that will be searched. For this example, we will create a table called "customers" with columns for "customer_id", "customer_first_name", "customer_last_name", "customer_email" and "customer_gender". Below you can find .sql script for create customers table and it will insert some sample data into that table.


--
-- Database: `testing`
--

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

--
-- Table structure for table `customers`
--

CREATE TABLE `customers` (
  `customer_id` int(11) NOT NULL,
  `customer_first_name` varchar(200) NOT NULL,
  `customer_last_name` varchar(200) NOT NULL,
  `customer_email` varchar(300) NOT NULL,
  `customer_gender` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `customers`
--

INSERT INTO `customers` (`customer_id`, `customer_first_name`, `customer_last_name`, `customer_email`, `customer_gender`) VALUES
(1, 'Mathilda', 'Garnam', 'mgarnam0@rediff.com', 'Female'),
(2, 'Tymon', 'McEniry', 'tmceniry1@free.fr', 'Male'),
(3, 'Margarette', 'Danilyak', 'mdanilyak2@joomla.org', 'Female'),
(4, 'Ermanno', 'Huebner', 'ehuebner3@wikipedia.org', 'Male'),
(5, 'Agnes', 'Barabich', 'abarabich4@delicious.com', 'Female'),
(6, 'Hamil', 'De Zuani', 'hdezuani5@hostgator.com', 'Male'),
(7, 'Corrie', 'Althorpe', 'calthorpe6@themeforest.net', 'Female'),
(8, 'Ricard', 'Dumelow', 'rdumelow7@china.com.cn', 'Male'),
(9, 'D\'arcy', 'Crayton', 'dcrayton8@furl.net', 'Male'),
(10, 'Kayle', 'Stonier', 'kstonier9@thetimes.co.uk', 'Female'),
(11, 'Julissa', 'Bogeys', 'jbogeysa@w3.org', 'Female'),
(12, 'Saul', 'Hyam', 'shyamb@senate.gov', 'Male'),
(13, 'Saleem', 'Pettengell', 'spettengellc@si.edu', 'Male'),
(14, 'Ives', 'Osmon', 'iosmond@forbes.com', 'Male'),
(15, 'Wendie', 'Acton', 'wactone@army.mil', 'Female'),
(16, 'Ches', 'Redd', 'creddf@un.org', 'Male'),
(17, 'Sarine', 'Cossum', 'scossumg@hubpages.com', 'Female'),
(18, 'Farly', 'Arsmith', 'farsmithh@linkedin.com', 'Male'),
(19, 'Althea', 'Tavernor', 'atavernori@printfriendly.com', 'Female'),
(20, 'Gayla', 'Billes', 'gbillesj@miitbeian.gov.cn', 'Female'),
(21, 'Teodoor', 'Shreenan', 'tshreenank@hp.com', 'Male'),
(22, 'Rich', 'Frusher', 'rfrusherl@cbc.ca', 'Male'),
(23, 'Lissie', 'Glazier', 'lglazierm@elpais.com', 'Female'),
(24, 'Glyn', 'Dealey', 'gdealeyn@unesco.org', 'Male'),
(25, 'Kathy', 'Swansborough', 'kswansborougho@amazon.de', 'Female'),
(26, 'Dudley', 'Hopkyns', 'dhopkynsp@mozilla.com', 'Male'),
(27, 'Byran', 'Ealles', 'beallesq@engadget.com', 'Male'),
(28, 'Kenon', 'MacGray', 'kmacgrayr@stumbleupon.com', 'Male'),
(29, 'Sibilla', 'Norres', 'snorress@smugmug.com', 'Female'),
(30, 'Melita', 'Redman', 'mredmant@a8.net', 'Female'),
(31, 'Ki', 'Brydson', 'kbrydsonu@google.ca', 'Female'),
(32, 'Bernardine', 'Follis', 'bfollisv@unc.edu', 'Female'),
(33, 'Farleigh', 'Sudy', 'fsudyw@unc.edu', 'Male'),
(34, 'Belle', 'Dearness', 'bdearnessx@google.co.uk', 'Female'),
(35, 'Onfre', 'Kee', 'okeey@archive.org', 'Male');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `customers`
--
ALTER TABLE `customers`
  ADD PRIMARY KEY (`customer_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `customers`
--
ALTER TABLE `customers`
  MODIFY `customer_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=36;


Step 2: Setting up the Server


Next, we will set up the server using Node.js. We will use the Express framework to handle the HTTP requests and responses. You can install Express using npm, the package manager for Node.js, by running the following command in your terminal:


cd f:

In my computer, We will create node application in f: drive, so we have goes into this f: drive.


cd node

After this we have goes into node in which we will create Ajax Live data Search Node Application.


mkdir ajax_live_data_search

This command will create ajax_live_data_search directory under node directory.


cd ajax_live_data_search

After this we have goes inti this ajax_live_data_search directory in which we will download different node module.


npm install express mysql

This command will download Node Express Module and MySQL Module under this ajax_live_data_search directory.





After installing Express, create a new file called "app.js" and add the following code:

app.js

const express = require('express');

const mysql = require('mysql');

const app = express();

const port = 3000;

const pool = mysql.createPool({
	connectionLimit : 10,
	host : 'localhost',
	user : 'root',
	password : '',
	database : 'testing'
});

app.get('/', (request, response) => {

	response.sendFile(__dirname + '/index.html');

});

app.listen(port, () => {

	console.log(`Server listening on port ${port}`);

});


This code sets up a basic Express server that listens on port 3000. You can test that the server is working by running "node app.js" in your terminal and navigating to "http://localhost:3000" in your browser and it will load HTML content of index.html file.

Step 3: Implementing the Ajax Live Search


Now we will implement the Ajax live search feature. We will use Vanilla JavaScript to make Ajax requests to the server and update the search results in real-time. You can include Vanilla JavaScript in your index.html file by adding the following code:

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Ajax Live Data Search in Node.js with MySql</title>
    <link href="https://getbootstrap.com/docs/5.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
    <div class="container mt-5 mb-5">
        <h1 class="text-primary text-center"><b>Ajax Live Data Search in Node.js with MySql</b></h1>
        <div class="mt-3 mb-3">
            <div class="card">
                <div class="card-header">Customer Data</div>
                <div class="card-body">
                    <div class="mb-3">
                        <input type="text" id="search" placeholder="Search..." class="form-control" autocomplete="off">
                        <table class="table table-bordered mt-3">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Email</th>
                                    <th>Gender</th>
                                </tr>
                            </thead>
                            <tbody id="results">

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
<script type="text/javascript">

const searchInput = document.querySelector('#search');

const results_body = document.querySelector('#results');

load_data();

function load_data(query = '')
{
    const request = new XMLHttpRequest();

    request.open('GET', `/search?q=${query}`);

    request.onload = () => {

        const results = JSON.parse(request.responseText);

        let html = '';

        if(results.length > 0)
        {
            results.forEach(result => {
                html += `
                <tr>
                    <td>`+result.customer_id+`</td>
                    <td>`+result.customer_first_name+`</td>
                    <td>`+result.customer_last_name+`</td>
                    <td>`+result.customer_email+`</td>
                    <td>`+result.customer_gender+`</td>
                </tr>
                `;
            });
        }
        else
        {
            html += `
            <tr>
                <td colspan="5" class="text-center">No Data Found</td>
            </tr>
            `;
        }

        results_body.innerHTML = html;

    };

    request.send();
}

searchInput.addEventListener('input', () => {

    const query = searchInput.value;

    load_data(query);

});

</script>


This code listens for keyup events on the search input field and makes an Ajax request to the server with the search query. The server responds with a JSON object containing the search results, which are then displayed in the search results list.

To handle the Ajax requests on the server, add the following code to "app.js":

app.js

app.get('/search', (request, response) => {

	const query = request.query.q;

	var sql = '';

	if(query != '')
	{
		sql = `SELECT * FROM customers WHERE customer_first_name LIKE '%${query}%' OR customer_last_name LIKE '%${query}%' OR customer_email LIKE '%${query}%'`;
	}
	else
	{
		sql = `SELECT * FROM customers ORDER BY customer_id`;
	}

	pool.query(sql, (error, results) => {

		if (error) throw error;

		response.send(results);

	});

});


This code creates a MySQL connection and listens for GET requests to "/search". It retrieves the search query from the GET request URL and executes a SQL query to search for customers whose first name, last name or email matches the query. The results are returned as a JSON object.

Step 4: Run Node Application


So here our code is ready now for check output in the browser, we have goes to terminal and run following command.


node app.js


This command will start node server and we can access this node application in browser by this http://localhost:3000 url.

Conclusion


In this article, we have shown you how to implement an Ajax live search feature using Node.js and MySQL. By using these technologies, you can build responsive and efficient web applications that provide a great user experience. With a few lines of code, you can easily add this feature to your web application and improve its functionality.

Complete Source Code


app.js



const express = require('express');

const mysql = require('mysql');

const app = express();

const port = 3000;

const pool = mysql.createPool({
	connectionLimit : 10,
	host : 'localhost',
	user : 'root',
	password : '',
	database : 'testing'
});

app.get('/', (request, response) => {

	response.sendFile(__dirname + '/index.html');

});

app.get('/search', (request, response) => {

	const query = request.query.q;

	var sql = '';

	if(query != '')
	{
		sql = `SELECT * FROM customers WHERE customer_first_name LIKE '%${query}%' OR customer_last_name LIKE '%${query}%' OR customer_email LIKE '%${query}%'`;
	}
	else
	{
		sql = `SELECT * FROM customers ORDER BY customer_id`;
	}

	pool.query(sql, (error, results) => {

		if (error) throw error;

		response.send(results);

	});

});

app.listen(port, () => {

	console.log(`Server listening on port ${port}`);

});


index.html



<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Ajax Live Data Search in Node.js with MySql</title>
    <link href="https://getbootstrap.com/docs/5.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
    <div class="container mt-5 mb-5">
        <h1 class="text-primary text-center"><b>Ajax Live Data Search in Node.js with MySql</b></h1>
        <div class="mt-3 mb-3">
            <div class="card">
                <div class="card-header">Customer Data</div>
                <div class="card-body">
                    <div class="mb-3">
                        <input type="text" id="search" placeholder="Search..." class="form-control" autocomplete="off">
                        <table class="table table-bordered mt-3">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Email</th>
                                    <th>Gender</th>
                                </tr>
                            </thead>
                            <tbody id="results">

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
<script type="text/javascript">

const searchInput = document.querySelector('#search');

const results_body = document.querySelector('#results');

load_data();

function load_data(query = '')
{
    const request = new XMLHttpRequest();

    request.open('GET', `/search?q=${query}`);

    request.onload = () => {

        const results = JSON.parse(request.responseText);

        let html = '';

        if(results.length > 0)
        {
            results.forEach(result => {
                html += `
                <tr>
                    <td>`+result.customer_id+`</td>
                    <td>`+result.customer_first_name+`</td>
                    <td>`+result.customer_last_name+`</td>
                    <td>`+result.customer_email+`</td>
                    <td>`+result.customer_gender+`</td>
                </tr>
                `;
            });
        }
        else
        {
            html += `
            <tr>
                <td colspan="5" class="text-center">No Data Found</td>
            </tr>
            `;
        }

        results_body.innerHTML = html;

    };

    request.send();
}

searchInput.addEventListener('input', () => {

    const query = searchInput.value;

    load_data(query);

});

</script>



Wednesday, 3 August 2022

A Step-by-Step Guide to Convert XML to JSON by using Online tool

A Step-by-Step Guide to Convert XML to JSON by using Online tool

If you're here to know the step-by-step guide to converting XML to JSON by using the online tool, then this article is for sure going to help you.

In this article, we will be discussing what these languages are, how they’re different and why conversion between them is necessary. We will also look at an effective and practical method to convert XML to JSON.

What Do You Mean by XML?


XML stands for ‘extensible markup language’. It is a markup language similar to HTML, except for the difference that the latter is used to specify how data is displayed whereas XML functions more to store data instead.

XML is best known for storing the data but the heavy data makes it a little slower to work. That is when a higher transfer speed is needed to transfer the data. Due to the lower speed, it makes you switch to the JSON that has a faster speed.

What Do You Mean By JSON?


JSON is a JavaScript Object Notation. It is a format that is comparatively lightweight than XML. Also, it is easily understandable by humans, which means it is a reader-friendly language. It is also way easier for the computer to process this language as it stores data in form of key pairs.





How Does an XML to JSON Converter Help You?


The XML to JSON converter is primarily concerned with translating XML data strings to JSON objects. The converter accurately converts all types of XML attributes, messages, comments, DOCTYPE, and other expressions. It is a precise, secure, and quick method of converting XML to JSON.

How can one convert XML to JSON?


There can be three conversion procedures to convert the XML to JSON that are briefly described here for your better understanding;

  1. By Manual Coding: Manual coding is one of the safest and most accurate methods of converting XML to JSON. It would require hard work, expert guidance, advanced skills, and extra effort and will consume more time than is very much an ineffective approach. Is worthy if you're the master of this particular language and have good hands-on practicing it then you can go for it only.
  2. Using External Libraries: External libraries can be another smart option if you want to deal with XML to JSON conversions. Most of the time Python libraries are preferred for this purpose. But this again has to be done by a person who has enough skills.
  3. Using Online Tools: Online tools can help you do wonders when it comes to performing conversion tasks. They can do the whole thing in a matter of seconds, which can save you considerable time.

It can be highly productive and time-saving for anyone who is a beginner to use a tool to convert XML code to JSON code. The thing that should be taken into consideration while converting is that you’ll have to remove the namespaces before the conversion takes place.

A Step-By-Step Procedure To Convert XML To JSON By Using An Online Tool:


A Step-by-Step Guide to Convert XML to JSON by using Online tool

The tools to convert XML to JSON are usually quite easy to understand and operate. Converting an XML to JSON is not tricky anymore as it can be done through online tools. You can perform the conversion on such tools by following a couple of simple steps.

  1. You'll just need to copy and then paste the XML code into the input box.
  2. Now, you'll click the Convert XML to JSON button to get the task done.
  3. The results will generate in a separate output box or in the same box as the input.

It has to be remembered that the exact working of the tools will be different. However, it will be along the lines of this generic procedure.

Bottom Line:


So, there you have it.

There are different ways in which you can convert XML to JSON. We mentioned those methods in the post above as well.

However, the quickest and easiest way to do it is to use online tools. As compared to the other methods, this way is the fastest since it only takes some seconds (or minutes, at most) to convert the input.

Top 5 Reasons to Choose Node.js for Product Development

top-5-reasons-to-choose-nodejs-for-product-development

Node.js is a prevalent runtime environment that allows the implementation of JavaScript code. It enables consistent, two-way communication between the client and server, which is how it reduces the work pressure among them.

Node.js provides exceptional support and unique features that make it a favorite among developers and business owners.

Are you interested in utilizing this technology for your next project? If you are, it’ll do you well to know its advantages before you try to hire a NodeJS development company.

5 Benefits That Make Node.js An Excellent Option


1. It Is Scalable


Node.js is great for single-page, data streaming, and JSON-based apps because it’s a scalable environment. Microservices allow it to separate an application into finer processes.

Several teams can take over these processes to develop them in tune with the increasing user requests. Operations don’t lag due to quicker development, leading to increased users.

2. It Is Fast


Node.js runs on Google's V8 engine, which saves development time by letting JavaScript code be converted to machine code. Therefore, product development with Node.js means convenient management of far more parallel connections.

Many companies have reported that hiring a NodeJS development company doubled their request processing speeds.

3. It Will Save You Money


Many web development companies receive inquiries regarding Node.js app development. The cost-benefit analysis they provide shows that Node.js development is more economical than anything else out there.

It also has a smaller memory footprint than PHP or Java servers. Node.js servers save RAM and hardware resources by running on an event-driven loop.





4. It Comes With Continuous Support


Node.js releases undergo active maintenance from the date of their entries to the next eighteen months. The development team takes care of every bug fix and security update during this period.

Over half the developer generation strategizes for long-term support as well, making Node.js the best option without a doubt.

5. It Enables Convenient Sharing


Another significant benefit of Node.js is its package manager, NPM, which eases sharing. The convenient sharing gives an additional boost to project development speed. It is one of the top reasons web development companies prefer this runtime environment.

To Conclude


A quick, convenient, and scalable JS environment like Node.js is famous for several reasons. It should be no surprise why many developers consider it the preferable option for software product development.

However, hiring an experienced NodeJS development company is the best way to get the results you seek for your project.

Author bio: Tom Hardy is a Node.js professional at SparxIT with 5 years of experience. He likes reading about emerging trends and technologies when he's not working.

Thursday, 7 July 2022

Export MySQL Data to CSV File using Node.js Express


This tutorial on Export Data to CSV file using Node js Express Application and in this tutorial, you will learn how to export data in CSV file from MySQL Database table in Node.js Application.

In our Node Web Application, sometimes we have to export data from MySQL database. So at that time CSV file format is the best option for exporting data from MySQL Database, so for this here in our Node.js Express Application, we will export MySQL data to CSV file using Node.js Application.

So if you have follow this tutorial, then this tutorial will helps you in easy way to exporting mysql database table data in CSV file using Node JS Express framework.

In this Node.js tutorial on export data to CSV file, we will use body-parser and json2csv node module under this node application, and by using this both module we will first export data to CSV file.

  • Fetch data from MySQL and display on Web page in HTML table format using Node.js & MySQL
  • Fetch Data from MySQL table and convert into JSON format
  • Convert JSON data to CSV format using json2csv node module
  • Export MySQL data to CSV file and download CSV file using Node.js

Export MySQL Data to CSV File using Node.js Express

For Export MySQL data to CSV file in Node.js, so you have follow below steps.

  1. MySQL Table Structure
  2. Download and Install Node.js Express framework
  3. Create MySQL Database Connection
  4. Install body-parser & json2csv Module
  5. Create Routes
  6. Create Views File
  7. Check Output in the browser




Step 1 - MySQL Table Structure


For start this tutorial, first we have to create table in MySQL table for export data to CSV file format in Node.js, so for create table in MySQL database, we have to run following script in your phpmyadmin area and it will create sample_data table with pre inserting of sample data and we will export that data to CSV file using Node js.


--
-- Database: `testing`
--

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

--
-- Table structure for table `sample_data`
--

CREATE TABLE `sample_data` (
  `id` int(10) NOT NULL,
  `first_name` varchar(250) NOT NULL,
  `last_name` varchar(250) NOT NULL,
  `age` varchar(30) NOT NULL,
  `gender` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `sample_data`
--

INSERT INTO `sample_data` (`id`, `first_name`, `last_name`, `age`, `gender`) VALUES
(1, 'John', 'Smith', '26', 'Male'),
(2, 'Donna', 'Hubber', '24', 'Female'),
(3, 'Peter', 'Parker', '28', 'Male'),
(4, 'Tom ', 'Muddy', '28', 'Male'),
(5, 'Desmond', 'Taylor', '36', 'Male'),
(6, 'Willie', 'Hudson', '24', 'Male'),
(7, 'Harold', 'Avila', '29', 'Male'),
(8, 'Kathryn', 'Moon', '22', 'Female'),
(9, 'Maria', 'Brewer', '26', 'Female'),
(10, 'Carma', 'Holland', '25', 'Female'),
(11, 'Patrick', 'Michel', '32', 'Male');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `sample_data`
--
ALTER TABLE `sample_data`
  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;





Step 2 - Download and Install Node.js Express framework


In this Node.js tutorial, we have use Express.js Framework, So first we need to download and install Node.js Express framework. So for this, first we have to go into directory in which we have run our node code and under that directory, we have to create csv_export directory and then after we have goes into that directory, so for this, we have to run following command.


mkdir csv_export
cd csv_export


Once we have goes into csv_export directory, now first we wan to download and install node express genderator, so for this, in the command prompt we have to run following command, which will download and install node.js express generator.


npm install -g express-generator


Next we want to download and install node.js express framework, so for this in the command prompt we have to run following command which will download and install node.js express framework under autocomplete directory.


npx express --view=ejs


In this downloaded Node.js Express framework, we have use ejs template engine for display HTML output in the browser and once we have run this command then it will display following node.js express directory structure which you can seen below.


create : public\
   create : public\javascripts\
   create : public\images\
   create : public\stylesheets\
   create : public\stylesheets\style.css
   create : routes\
   create : routes\index.js
   create : routes\users.js
   create : views\
   create : views\error.ejs
   create : views\index.ejs
   create : app.js
   create : package.json
   create : bin\
   create : bin\www

   install dependencies:
     > npm install

   run the app:
     > SET DEBUG=crud:* & npm start


And lastly under node.js express download and install process we have to run following command for install required node.js default module for express framework.


npm install


After run above command, so here our Node.js Express download and install process is completed.

Step 3 - Create MySQL Database Connection


After download and install Node.js Express framework, now we want to connect this applicatioin with MySQL Database, so for make MySQL database connection, first we have to download node mysql module. So for this, we have to run following command in command prompt.


npm install mysql


Once Node Mysql module has been install in our node express application, next we need to create one database.js file for create mysql database connection, and under this file, we have to define MySQL database configuration for connection node express application with MySQL database.

database.js

const mysql = require('mysql');

var connection = mysql.createConnection({
	host : 'localhost',
	database : 'testing',
	user : 'root',
	password : ''
});

connection.connect(function(error){
	if(error)
	{
		throw error;
	}
	else
	{
		console.log('MySQL Database is connected Successfully');
	}
});

module.exports = connection;


Step 4 - Install body-parser & json2csv Module


In this Node tutorial for Export data to CSV, here we need to download some extra node module like body-parser and json2csv module. So for download this module, we have goes to command prompt and run following command.


npm install body-parser json2csv --save


In this above command json2csv module has been used for convert a JSON data to CSV data and convert CSV data to JSON format.

And body-parser module is a npm library which has been process data and send that data to HTTP request body.

So by isntalling this both module under this Node Express framework, we can able to export MySQL database to CSV file format.

Step 5 - Create Routes


In the Node Express framework, routes file has been used for handle HTTP request. Here when we have download express framework, then you will get index.js default files under routes directory.

Here we have to open routes/index.js file and under this file, we have to include database connection file and json2csv node module also.

After this, in the main route which has been load views/index.ejs file for display output in the browser. So when file has been load then it will fetch data from MySQL table and display data on the web page in HTML table format.

And for handle request for export data to csv file, we have to create another route and under that route first it will fetch data from mysql table, and convert that data into JSON format and lasly by using json2csv module it will convert json data to csv format and downlaod csv file in local computer.

routes/index.js

var express = require('express');
var router = express.Router();

var database = require('../database');

var data_exporter = require('json2csv').Parser;

/* GET home page. */
router.get('/', function(req, res, next) {

    database.query('SELECT * FROM sample_data', function(error, data){

        res.render('index', { title: 'Express', sample_data:data });

    });
    
});

router.get('/export', function(request, response, next){

    database.query('SELECT * FROM sample_data', function(error, data){

        var mysql_data = JSON.parse(JSON.stringify(data));

        //convert JSON to CSV Data

        var file_header = ['First Name', 'Last Name', 'Age', 'Gender'];

        var json_data = new data_exporter({file_header});

        var csv_data = json_data.parse(mysql_data);

        response.setHeader("Content-Type", "text/csv");

        response.setHeader("Content-Disposition", "attachment; filename=sample_data.csv");

        response.status(200).end(csv_data);

    });

});

module.exports = router;


Step 6 - Create Views File


In the Node.js Express framework, views directory file has been used for display html output in the browser. In this tutorial, we have use EJS template engine for display HTML output in the browser. Here we will use views/index.ejs default file, and under this file, first we will display mysql data in html table format and then after, we have to create on link for export data to csv file which will send http get request to routes for export data to csv file in Node.js Express application.

views/index.ejs

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <title>How to Export MySQL Data to CSV in Node.js</title>
    </head>
    <body>
        <div class="container">
            <h1 class="text-center text-primary mt-3 mb-3">How to Export MySQL Data to CSV in Node.js</h1>

            <div class="card">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-10">Sample Data</div>
                        <div class="col-md-2">
                            <a href="/export" class="btn btn-success btn-sm float-end">Export to CSV</a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                        
                    <table class="table table-bordered">
                        <tr>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Age</th>
                            <th>Gender</th>
                        </tr>
                        <% sample_data.forEach(function(data){ %>
                        <tr>
                            <td><%= data.first_name %></td>
                            <td><%= data.last_name %></td>
                            <td><%= data.age %></td>
                            <td><%= data.gender %></td>
                        </tr>
                        <% }); %>
                    </table>

                </div>
            </div>
        </div>
  </body>
</html>


Step 7 - Check Output in the browser


Once we have follow all above step, so we are able to check output in the browser. So for check output in the browser, first we have goes to command prompt and run following command.


npm start


This command will start Node.js server and then after we can goes to browser and following URL.


http://localhost:3000/


So once we have hit above url then it will display MySQL table data on web page in HTML table format and above this data, we can see on export button. So when we have click on export button then it will export mysql data into CSV file format using Node js express application.





Friday, 16 October 2020

How to Convert CSV to JSON in PHP


This is simple and short tutorial on How do we convert CSV file data into JSON format in PHP. In this world of web programming, sometimes we have to make feature like fetch data from CSV file and insert that CSV file data into Mysql database then at that time we have need to convert CSV to JSON. The main purpose of this tutorial is to learn how can we easy way to convert CSV data or file to JSON object using PHP script.

Advantages of CSV


  1. CSV files can be opened or edited by text editors like notepad.
  2. In data-warehouse, CSV follows a reasonably flat, simple schema.
  3. Any programing language to parse CSV data is trivial, generating it's extremely easy.
  4. CSV is safe and may clearly differentiate between the numeric values and text. CSV doesn't manipulate data and stores it as-is.
  5. In CSV, you write column headers just one occasion where as in Excel, you've got to possess a start tag and end tag for every column in each row.
  6. Importing CSV files are often much faster, and it also consumes less memory.
  7. It's easy to programmatically manipulate CSV since, after all, they're simple text files.
  8. CSV are often opened with any text editor in Windows like notepad, MS Excel, Microsoft Works 9, etc.

Advantages of JSON


  1. JSON is a portable that means it can be parse and write are available in many programming languages like JavaScript.
  2. By using JSON we can online transfer large data from source to destination in the form of array or objects.
  3. IN JSON we can transfer data in plain text or unformatted data like comma speratted or delimited data.
  4. JSON is better that XML, this is because it has more sufficient space than XML data structure.
  5. JSON has no tag name and it has structure which is nested braces instead of verbose tags.
  6. In exchange of data JSON is faster than XML.


So here we have seen benefits of CSV and JSON data and both are mainly used for data exchange. But if you have work on any web services than JSON data is mostly used for transmit or exchange of data on the web. So if you have data in CSV file and you have to exchange that data then you must convert that data into JSON format and you can easily exchange data online.

In PHP language there many functions are available for parse or read data from CSV file and then convert that data into PHP array and lastly for convert data into JSON then we can use json_encode() function.



Sample Input CSV Data



Company Name,Address,City,State,ZIP/PIN CODE,Country,Website,Industry,First Name,Last Name,Phone Number,Designation,Email
Cougar Investment,3570 Thunder Road,Mountain View,CA,94041,USA,dealtechs.com,Animal care and service worker,Devin,Taylor,650-564-1816,Animal care and service worker,DevinRTaylor@armyspy.com
Robert Hall,1729 Lyndon Street,Slatington,PA,18080,USA,toksalgida.com,Media,Ruby,Gibson,610-767-5251,News anchor,RubyBGibson@armyspy.com



index.php



<?php

$error = '';

if(isset($_POST["upload_file"]))
{
  if($_FILES['file']['name'])
  {
    $file_array = explode(".", $_FILES['file']['name']);

    $file_name = $file_array[0];

    $extension = end($file_array);

    if($extension == 'csv')
    {
      $column_name = array();

      $final_data = array();

      $file_data = file_get_contents($_FILES['file']['tmp_name']);

      $data_array = array_map("str_getcsv", explode("\n", $file_data));

      $labels = array_shift($data_array);

      foreach($labels as $label)
      {
        $column_name[] = $label;
      }

      $count = count($data_array) - 1;

      for($j = 0; $j < $count; $j++)
      {
        $data = array_combine($column_name, $data_array[$j]);

        $final_data[$j] = $data;
      }

      header('Content-disposition: attachment; filename='.$file_name.'.json');

      header('Content-type: application/json');

      echo json_encode($final_data);

      exit;
    }
    else
    {
      $error = 'Only <b>.csv</b> file allowed';
    }
  }
  else
  {
    $error = 'Please Select CSV File';
  }
}

?>

<!DOCTYPE html>
<html>
  	<head>
    	<title>Convert CSV to JSON using PHP</title>
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="http://code.jquery.com/jquery.js"></script>
    	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  	</head>
  	<body>
  		<div class="container">
  			<br />
  			<br />
    		<h1 align="center">Convert CSV to JSON using PHP</h1>
    		<br />
    		<div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">Select CSV File</h3>
          </div>
          <div class="panel-body">
            <?php
            if($error != '')
            {
              echo '<div class="alert alert-danger">'.$error.'</div>';
            }
            ?>
            <form method="post" enctype="multipart/form-data">
              <div class="col-md-6" align="right">Select File</div>
              <div class="col-md-6">
                <input type="file" name="file" />
              </div>
              <br /><br /><br />
              <div class="col-md-12" align="center">
                <input type="submit" name="upload_file" class="btn btn-primary" value="Upload" />
              </div>
            </form>
          </div>
        </div>
    	</div>
    	
  	</body>
</html>



Output JSON Data



[
  {
    "Company Name": "Cougar Investment",
    "Address": "3570 Thunder Road",
    "City": "Mountain View",
    "State": "CA",
    "ZIP/PIN CODE": "94041",
    "Country": "USA",
    "Website": "dealtechs.com",
    "Industry": "Animal care and service worker",
    "First Name": "Devin",
    "Last Name": "Taylor",
    "Phone Number": "650-564-1816",
    "Designation": "Animal care and service worker",
    "Email": "DevinRTaylor@armyspy.com"
  },
  {
    "Company Name": "Robert Hall",
    "Address": "1729 Lyndon Street",
    "City": "Slatington",
    "State": "PA",
    "ZIP/PIN CODE": "18080",
    "Country": "USA",
    "Website": "toksalgida.com",
    "Industry": "Media",
    "First Name": "Ruby",
    "Last Name": "Gibson",
    "Phone Number": "610-767-5251",
    "Designation": "News anchor",
    "Email": "RubyBGibson@armyspy.com"
  }
]



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.