In our previous tutorial, we have explained to develop Invoice System with PHP & MySQL. In this tutorial, we will explain How To Develop Live Chat System with Ajax, PHP & MySQL.
Chat System or Chat application is mainly used to communicate with people like friends, customers, colleagues etc. It is an important part of any business as most of company have their chat system integrated into their websites to communicate with their clients to assist them regarding services and resolve issues.
Also, read:
- Create Live Editable Table with jQuery, PHP and MySQL
- Build Invoice System with PHP & MySQL
- Live Add Edit Delete datatables Records with Ajax, PHP and MySQL
So if you’re looking for developing your own chat system then you’re here at right place. In this tutorial you will learn how to develop live chat system with Ajax, PHP and MySQL. We will cover this tutorial in easy steps to develop live chat demo to create complete chat system.
As we will cover this tutorial with live example to build live chat system with Ajax, PHP & MySQL, so the major files for this example is following.
- index.php
- login.php
- chat.js
- chat_action.php
- logout.php
- Chat.php
Step1: Create Database Tables
We will create MySQL database tables that’s used to build chat system. So first we will create table chat_users to store users login information.
CREATE TABLE `chat_users` ( `userid` int(11) NOT NULL, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `avatar` varchar(255) NOT NULL, `current_session` int(11) NOT NULL, `online` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
we will also insert few users record using below insert query.
INSERT INTO `chat_users` (`userid`, `username`, `password`, `avatar`, `current_session`, `online`) VALUES (1, 'Rose', '123', 'user1.jpg', 3, 0), (2, 'Smith', '123', 'user2.jpg', 1, 0), (3, 'adam', '123', 'user3.jpg', 1, 0), (4, 'Merry', '123', 'user4.jpg', 0, 0), (5, 'katrina', '123', 'user5.jpg', 0, 0), (6, 'Rhodes', '123', 'user6.jpg', 0, 0);
We will create chat table to store chat details.
CREATE TABLE `chat` ( `chatid` int(11) NOT NULL, `sender_userid` int(11) NOT NULL, `reciever_userid` int(11) NOT NULL, `message` text NOT NULL, `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` int(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
We will also create chat_login_details table to store logged in chat activity.
CREATE TABLE `chat_login_details` ( `id` int(11) NOT NULL, `userid` int(11) NOT NULL, `last_activity` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `is_typing` enum('no','yes') NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Step2: Chat User Login
First we will create chat login interface in login.php to login to chat system.
<div class="row"> <div class="col-sm-4"> <h4>Chat Login:</h4> <form method="post"> <div class="form-group"> <?php if ($loginError ) { ?> <div class="alert alert-warning"><?php echo $loginError; ?></div> <?php } ?> </div> <div class="form-group"> <label for="username">User:</label> <input type="username" class="form-control" name="username" required> </div> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" class="form-control" name="pwd" required> </div> <button type="submit" name="login" class="btn btn-info">Login</button> </form> </div> </div>
We will implement login functionality on form submit in login.php. We will include Chat.php module to handle user login with method loginUsers(). We will store user login details in SESSION variables for further use in system.
$loginError = ''; if (!empty($_POST['username']) && !empty($_POST['pwd'])) { include ('Chat.php'); $chat = new Chat(); $user = $chat->loginUsers($_POST['username'], $_POST['pwd']); if(!empty($user)) { $_SESSION['username'] = $user[0]['username']; $_SESSION['userid'] = $user[0]['userid']; $lastInsertId = $chat->insertUserLoginDetails($user[0]['userid']); $_SESSION['login_details_id'] = $lastInsertId; header("Location:index.php"); } else { $loginError = "Invalid username or password!"; } }
Step3: Create Chat System HTML
In index.php, we will include Bootstrap, jQuery and CSS files to create chat system interface with Bootstrap.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <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.5/js/bootstrap.min.js"></script> <link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.2/css/font-awesome.min.css'> <link href="css/style.css" rel="stylesheet" id="bootstrap-css"> <script src="js/chat.js"></script>
After user logged in, it will redirect to index.php where we will display chat system with users list and user chat details. So now we will create chat system HTML to load chat details from MySQL database tables after successful user login.
So first we will get details of current logged in chat user details from database table chat_users using chat method getUserDetails() from Chat.php.
<div id="profile"> <?php include ('Chat.php'); $chat = new Chat(); $loggedUser = $chat->getUserDetails($_SESSION['userid']); echo '<div class="wrap">'; $currentSession = ''; foreach ($loggedUser as $user) { $currentSession = $user['current_session']; echo '<img id="profile-img" src="userpics/'.$user['avatar'].'" class="online" alt="" />'; echo '<p>'.$user['username'].'</p>'; echo '<i class="fa fa-chevron-down expand-button" aria-hidden="true"></i>'; echo '<div id="status-options">'; echo '<ul>'; echo '<li id="status-online" class="active"><span class="status-circle"></span> <p>Online</p></li>'; echo '<li id="status-away"><span class="status-circle"></span> <p>Away</p></li>'; echo '<li id="status-busy"><span class="status-circle"></span> <p>Busy</p></li>'; echo '<li id="status-offline"><span class="status-circle"></span> <p>Offline</p></li>'; echo '</ul>'; echo '</div>'; echo '<div id="expanded">'; echo '<a href="logout.php">Logout</a>'; echo '</div>'; } echo '</div>'; ?> </div>
Now we will get details of all chat user from database table chat_users using chat method chatUsers() from Chat.php and display users list.
<div id="contacts"> <?php echo '<ul>'; $chatUsers = $chat->chatUsers($_SESSION['userid']); foreach ($chatUsers as $user) { $status = 'offline'; if($user['online']) { $status = 'online'; } $activeUser = ''; if($user['userid'] == $currentSession) { $activeUser = "active"; } echo '<li id="'.$user['userid'].'" class="contact '.$activeUser.'" data-touserid="'.$user['userid'].'" data-tousername="'.$user['username'].'">'; echo '<div class="wrap">'; echo '<span id="status_'.$user['userid'].'" class="contact-status '.$status.'"></span>'; echo '<img src="userpics/'.$user['avatar'].'" alt="" />'; echo '<div class="meta">'; echo '<p class="name">'.$user['username'].'<span id="unread_'.$user['userid'].'" class="unread">'.$chat->getUnreadMessageCount($user['userid'], $_SESSION['userid']).'</span></p>'; echo '<p class="preview"><span id="isTyping_'.$user['userid'].'" class="isTyping"></span></p>'; echo '</div>'; echo '</div>'; echo '</li>'; } echo '</ul>'; ?> </div>
and finally we will get details of current active chat user’s chat from database table chat using chat method getUserChat() from Chat.php and display chat details.
<div class="contact-profile" id="userSection"> <?php $userDetails = $chat->getUserDetails($currentSession); foreach ($userDetails as $user) { echo '<img src="userpics/'.$user['avatar'].'" alt="" />'; echo '<p>'.$user['username'].'</p>'; echo '<div class="social-media">'; echo '<i class="fa fa-facebook" aria-hidden="true"></i>'; echo '<i class="fa fa-twitter" aria-hidden="true"></i>'; echo '<i class="fa fa-instagram" aria-hidden="true"></i>'; echo '</div>'; } ?> </div> <div class="messages" id="conversation"> <?php echo $chat->getUserChat($_SESSION['userid'], $currentSession); ?> </div>
Step4: Handle User Chat Reply
We will handle message send functionality in chat.js when click message send button and call function sendMessage()
$(document).on("click", '.submit', function(event) { var to_user_id = $(this).attr('id'); to_user_id = to_user_id.replace(/chatButton/g, ""); sendMessage(to_user_id); });
We will create a JavaScript function sendMessage() in chat.js in which we will make Ajax request to chat_action.php with action insert_chat to insert user chat to database and update user’s conversation with replied message.
function sendMessage(to_user_id) { message = $(".message-input input").val(); $('.message-input input').val(''); if($.trim(message) == '') { return false; } $.ajax({ url:"chat_action.php", method:"POST", data:{to_user_id:to_user_id, chat_message:message, action:'insert_chat'}, dataType: "json", success:function(response) { var resp = $.parseJSON(response); $('#conversation').html(resp.conversation); $(".messages").animate({ scrollTop: $('.messages').height() }, "fast"); } }); }
In chat_action.php, we will call chat method insertChat() to insert chat details.
<?php session_start(); include ('Chat.php'); if($_POST['action'] == 'insert_chat') { $chat->insertChat($_POST['to_user_id'], $_SESSION['userid'], $_POST['chat_message']); } ?>
The method insertChat() from Chat.pm to insert user chat.
<?php public function insertChat($reciever_userid, $user_id, $chat_message) { $sqlInsert = " INSERT INTO ".$this->chatTable." (reciever_userid, sender_userid, message, status) VALUES ('".$reciever_userid."', '".$user_id."', '".$chat_message."', '1')"; $result = mysqli_query($this->dbConnect, $sqlInsert); if(!$result){ return ('Error in query: '. mysqli_error()); } else { $conversation = $this->getUserChat($user_id, $reciever_userid); $data = array( "conversation" => $conversation ); echo json_encode($data); } } ?>
Step5: Update Chat User list Info
In chat.js, we will create function updateUserList() to update chat user list information like user online status by making Ajax request to chat_action.php.
function updateUserList() { $.ajax({ url:"chat_action.php", method:"POST", dataType: "json", data:{action:'update_user_list'}, success:function(response){ var obj = response.profileHTML; Object.keys(obj).forEach(function(key) { // update user online/offline status if($("#"+obj[key].userid).length) { if(obj[key].online == 1 && !$("#status_"+obj[key].userid).hasClass('online')) { $("#status_"+obj[key].userid).addClass('online'); } else if(obj[key].online == 0){ $("#status_"+obj[key].userid).removeClass('online'); } } }); } }); }
In chat_action.php, we will handle Ajax request action to return chat users information as JSON.
<?php $chat = new Chat(); if($_POST['action'] == 'update_user_list') { $chatUsers = $chat->chatUsers($_SESSION['userid']); $data = array( "profileHTML" => $chatUsers, ); echo json_encode($data); } ?>
Step6: Update Active User Chat Details
In chat.js, we will create function updateUserChat() to update active user chat details by making Ajax request to chat_action.php.
function updateUserChat() { $('li.contact.active').each(function(){ var to_user_id = $(this).attr('data-touserid'); $.ajax({ url:"chat_action.php", method:"POST", data:{to_user_id:to_user_id, action:'update_user_chat'}, dataType: "json", success:function(response){ $('#conversation').html(response.conversation); } }); }); }
In chat_action.php, we will handle Ajax request action to return chat details as JSON data response.
<?php $chat = new Chat(); if($_POST['action'] == 'update_user_chat') { $conversation = $chat->getUserChat($_SESSION['userid'], $_POST['to_user_id']); $data = array( "conversation" => $conversation ); echo json_encode($data); } ?>
Step7: Update User’s Unread Message Count
In chat.js, we will create function updateUnreadMessageCount() to update user unread message count by making Ajax request to chat_action.php.
function updateUnreadMessageCount() { $('li.contact').each(function(){ if(!$(this).hasClass('active')) { var to_user_id = $(this).attr('data-touserid'); $.ajax({ url:"chat_action.php", method:"POST", data:{to_user_id:to_user_id, action:'update_unread_message'}, dataType: "json", success:function(response){ if(response.count) { $('#unread_'+to_user_id).html(response.count); } } }); } }); }
In chat_action.php, we will handle Ajax request action to return user’s unread message count as JSON data response.
<?php $chat = new Chat(); if($_POST['action'] == 'update_unread_message') { $count = $chat->getUnreadMessageCount($_POST['to_user_id'], $_SESSION['userid']); $data = array( "count" => $count ); echo json_encode($data); } ?>
Step8: Update User Typing Status
In chat.js, we will handle user’s typing status by making Ajax request to chat_action.php to update typing as yes if user typing on input focus event.
$(document).on('focus', '.message-input', function(){ var is_type = 'yes'; $.ajax({ url:"chat_action.php", method:"POST", data:{is_type:is_type, action:'update_typing_status'}, success:function(){ } }); });
We will also update typing status as no if user stop typing on input blur event
$(document).on('blur', '.message-input', function(){ var is_type = 'no'; $.ajax({ url:"chat_action.php", method:"POST", data:{is_type:is_type, action:'update_typing_status'}, success:function() { } }); });
In chat_action.php, we will update user’s typing status to database table.
<?php $chat = new Chat(); if($_POST['action'] == 'update_typing_status') { $chat->updateTypingStatus($_POST["is_type"], $_SESSION["login_details_id"]); } ?>
The chat method updateTypingStatus() from Chat.php.
<?php public function updateTypingStatus($is_type, $loginDetailsId) { $sqlUpdate = " UPDATE ".$this->chatLoginDetailsTable." SET is_typing = '".$is_type."' WHERE id = '".$loginDetailsId."'"; mysqli_query($this->dbConnect, $sqlUpdate); } ?>
Step9: Get User Typing Status
In chat.js, we will create function showTypingStatus() to show user typing status by making Ajax request to chat_action.php.
function showTypingStatus() { $('li.contact.active').each(function(){ var to_user_id = $(this).attr('data-touserid'); $.ajax({ url:"chat_action.php", method:"POST", data:{to_user_id:to_user_id, action:'show_typing_status'}, dataType: "json", success:function(response){ $('#isTyping_'+to_user_id).html(response.message); } }); }); }
In chat_action.php, we will handle Ajax request action to return user’s user typing status as JSON data response.
<?php $chat = new Chat(); if($_POST['action'] == 'show_typing_status') { $message = $chat->fetchIsTypeStatus($_POST['to_user_id']); $data = array( "message" => $message ); echo json_encode($data); } ?>
The chat method fetchIsTypeStatus() from Chat.php.
<?php public function fetchIsTypeStatus($userId){ $sqlQuery = " SELECT is_typing FROM ".$this->chatLoginDetailsTable." WHERE userid = '".$userId."' ORDER BY last_activity DESC LIMIT 1"; $result = $this->getData($sqlQuery); $output = ''; foreach($result as $row) { if($row["is_typing"] == 'yes'){ $output = ' - Typing...'; } } return $output; } ?>
Step10: Handle Chat User Logout
In logout.php, we will handle user logout functionality and update user offline status.
<?php session_start(); include ('Chat.php'); $chat = new Chat(); $chat->updateUserOnline($_SESSION['userid'], 0); $_SESSION['username'] = ""; $_SESSION['userid'] = ""; $_SESSION['login_details_id']= ""; header("Location:index.php"); ?>
You will also like these tutorials:
You may also like:
- Build Live Chat System with Ajax, PHP & MySQL
- Create Event Calendar with jQuery, PHP and MySQL
- Build Invoice System with PHP & MySQL
- Push Notification System with PHP & MySQL
- Create Bootstrap Cards with PHP and MySQL
- Build Content Management System with PHP & MySQL
- Convert Unix Timestamp To Readable Date Time in PHP
- Ajax Drop Down Selection Data Load with PHP & MySQL
- Inventory Management System with Ajax, PHP & MySQL
- Drag and Drop File Upload using jQuery and PHP
- Load Dynamic Content in Bootstrap Popover with Ajax, PHP & MySQL
You can view the live demo from the Demo link and can download the full script from the Download link below.
Demo Download
1. Warning: Use of undefined constant MYSQL_ASSOC – assumed ‘MYSQL_ASSOC’ (this will throw an Error in a future version of PHP) in C:\wamp64\www\fb\Chat.php on line 30
2. Warning: mysqli_fetch_array() expects parameter 2 to be integer, string given in C:\wamp64\www\fb\Chat.php on line 30
I HAVE GOT ABOVE ERRORS WHILE I TRIED TO LOG IN AS adam 123 PLEASE HELP ME I WILL BE THANKFUL.
You can replace MYSQL_ASSOC with MYSQLI_ASSOC to fix this issue. Thanks!
I tweeted but I couldn’t see the download link
Try to reload the page after like or tweet if it is not displaying. Thanks!
How to download complete code in zip?
it’s fixed, you can download from download link in tutorial. thanks!
Thank you for the great article.
can you give me the chat code using php ajax.
thank you very much !
You can download complete code, thanks!
helo when i submit the chat room doesnt post data into the database
its working at my end. Please check if any error or warning at your end.
i can’t seem to find the chat.php. Can somebody help please??
Please download complete zip file. Thanks!
Hi where is zip file .
Can you send me link for download this.
You can download from download link at the end of tutorial. Thanks!
The first two chats I made went through and the rest nothing shows
And the system doesn’t give any error report
Please help me
Chat disabled in demo. You need to download code and run on your server. Thanks!
Chat is not working event I tried with number of users login I cant event see my own messages
its disabled to store chats on demo. You need to download complete project zip file and try on your server. Thanks!
Hi where is zip file .
Can you send me link for download this.
its located at the end of tutorial. thanks!
you can download the complete project code by download link, download link is located at the end of tutorial. thanks!
Hello
I can not download code for this tutorial (Build Live Chat System with Ajax, PHP & MySQL)
please guide me
The download link is at the end of tutorial. Thanks.
helo when i submit the chat room doesnt post data into the database
Please send more details to fix your. Its working example.
does not give an error but does not send information to the database. The same error is present in the demo.
In demo information store to database is disabled. Please check in your code if it is not commented. thanks!
Please sir how can I fix the sidebar is not compatible for mobile devices
You will have to make changes to work on all devices, thanks!
Online demo not working (Not reponsive), when I enter a chat, it does not even show up!
Chating disabled on demo. You need to download project files run on your server. thanks!
Dear hey . i like your work it is an excellent work. but it post only one message .
It’s working correctly at my end. Download code and run at your end. Thanks!
hello sir thanks a lot its very nice live chat system..
but at my end one problem arise one one time we send a message,
i can not send more than one time.. please fix this error.
I will check this and update you. thanks!
The problem is that the “chatid” in the “chat” table is not the primary key and it doesn’t increment itself, just adjust it.
make it primary and auto increment. thanks!
Hey, can you tell me where have you linked chat.js
The chat.js file is linked in index.php file. Thanks!
Hello! I was wondering if could work within a Codeigniter based site? I’ve been trying to implement a chatbot for weeks and having bad luck doing so. Was recommend this and wouldn’t mind trying it out!
I will try to implement same on Codeigniter and update you. thanks!
please, sir, this work is nice, but has one thing left, NEW USERS CANNOT SIGN UP, sir, please, review this
I will surely try to implement that. Thanks for suggestion!
how to add an attachment into chat
You need to handle functionality like form with file upload to send binary data to handle attachment send. Thanks!
I think style.CSS is not working when i run it on my own server. Can you help me out….
You can provide us your code to fix issue. thanks!
the chat system online and the is_typing is unstable.
please what can i do to fix it
You can try to do handle according to your requirement. thanks!
Can you fix the chatting delay…
if you send a chat it delay’s up to 2-3 seconds before the chat is sent
please tell me how to fix it..
We checking to fix it for you and update you. thanks!
very nice live chat
but i can not download it
You can download complete project from download link. thanks!
I download the project but every time I try to login with one of the provided users or create my own it says “invalid username and password ?
Any help with this?
Thanks Robert
You can send us the code to debug and fix issue. thanks!
I tested this code and this wont work in my server.
Some issue with login and if i get in – after 1 message system wont work.
[27-Mar-2020 11:22:24 UTC] PHP Warning: Cannot modify header information – headers already sent by (output started at /home/MYSERVER/public_html/chat2/header.php:1) in /home/MYSERVER/public_html/chat2/login.php on line 15
[27-Mar-2020 11:22:34 UTC] PHP Warning: mysqli_error() expects exactly 1 parameter, 0 given in /home/MYSERVER/public_html/chat2/Chat.php on line 85
Functions that send/modify HTTP headers must be invoked before any output is made. Check and make necessary changes. Check and pass correct connection with mysqli_error() to fix error. Thanks!
Hy sir
Great effort . can you send me download link i am unable to download this
you can download the complete project code by download link, download link is located at the end of tutorial. thanks!
Hy , i did not find getUserChat() function can you share code please or send me link.
you can download the complete project code by download link, download link is located at the end of tutorial. thanks!
I get this warning
Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\xampp\htdocs\chat\Chat.php on line 36
Error in query:
So I make a new variable
private $con = mysqli_connect(‘localhost’,’root’,””,”chat”);
and pass it as an arguement to mysqli_error().
But then it gives me an error that “PHP Fatal Error: Constant expression contains invalid operations”.
Can you tell me how the variable’s parameters should be?
The error was related to your SQL query, its not related to connection. Please check that and fix. thanks!
Hi. Excellent. I got the chat working in five minutes of set up. I liked in facebook, downloaded the code, set up database and that is all. Thanks a lot.
Great work! The sidepanel does not adjust with the screen sizes
Just wondering if your chat script is secure for a live site? Please advise.
Tried to install into a sub directory of root named chat and received 500 server error. Is this possible?
It’s for initial level, you will have enhance this to use securely. thanks!
I downloaded the zip, uploaded the files to my server.
I created the tables on my database, changed Chat.php > $user $password $database.
Primary keys and auto increment is set on all tables but…
I am unable to log in.
I get “Invalid username or password!” error.
Any ideas on a fix for this?
Try to debug, may there error that causing issue, thanks!
can we share files like image, video or audio
This is not handle in this example code, you can make changes for this to support. thanks!
can please show me how to include image sharing
and stikers to the messaging center
I am checking this and update you about this. thanks!
it send inly one message and never send again. i have tried install and uninstall several times
Please try to debug, may be there any error while running on your server. thanks!
You’ll need to update the table definition to auto increment the “chatid” on the chat table.
I cannot send more than one message and there is no return message , please suggest what can be done?
Try to debug , may be there any error that causing issue. It’s working fine in running demo. Thanks!
Is there a way to follow/unfollow folks along with using this chat
You can enhance according to your need. Thanks!
Hello!!
I already have a login user script locked in and just want to connect this code to what I have. How do I go about doing that so users dont have to login twice?
Thank ya
Hello Sir Thanks For this! It is very helpful. Sir I have recently made a social media platform using php where we can add photos text and can do many more things like a normal social media. Now i am coming up with chat system in that! I ve made a similar kind of chat system using php where chats are saved into my database. Sir I wanted to know how can i make it secured(encryted) so that all users can trust us that nobody can view their messages even we(admin) cannot read their chats. Sir can you please guide me? Thanking you in anticipation!
Thank you, it’s working fime
Thanks!
Fatal error: Uncaught Error: Undefined constant “MYSQL_ASSOC” in C:\xampp\htdocs\chat_system\Chat.php:27 Stack trace: #0 C:\xampp\htdocs\chat_system\Chat.php(45): Chat->getData(‘\r\n\t\t\tSELECT use…’) #1 C:\xampp\htdocs\chat_system\login.php(8): Chat->loginUsers(‘adam’, ‘123’) #2 {main} thrown in C:\xampp\htdocs\chat_system\Chat.php on line 27
need help
need to changes MYSQL_ASSOC to MYSQLI_ASSOC, thanks
Hey there!!
I already have login/register and would like to connect this script to that so users only have to login once. How do I accomplish this?
Thank ya
You will have handle this to work your registred users, you can make chanegs accordingly.
Really like the application you built keep up the good work !
Thanks!
can i know how to add the search function in it?
You can enahnce to add search with database as chat storing there in db.