How to Easily Make “Ajaxy” Chat application with PHP + SQL + jQuery
Today I will tell you about another chat system. After making old-style chat described in previous post I decided to make modern, pretty version. I made several enhancements:
- a) Login system. Now it using database to keep members. Also it have easy methods to take some necessary info about logged member.
- b) Chat interface. Now it much more user friendly. And show last added messages via toggling (based on jQuery). Looks fine.
- c) Inner code structure. Now here are good order. All libraries in ‘inc’ folder, all javascripts in ‘js’ folder, all template-related files in folder ‘templates’. More, class organization: now we have useful DB class, class of login system, chat class too.
- d) of code safety. Added necessary methods to protect from hack attacks. As example function process_db_input in our DB class.
So, as result – we will able to chat with our logged members. We will use database to store messages as usual.
Here is a sample:
Ok, download the example files and lets start coding !
Step 1. HTML
As usual, we start with the HTML.
This is input text form of our chat.
templates/chat_input.html
<form class="submit_form" method="post" action="" target="chat_res">
<div><input type="text" name="s_message" /><input type="submit" value="Say" name="s_say" /></div>
</form>
<div>You can type anything in chat</div>
<iframe name="chat_res" style="display:none;"></iframe>This is login form code.
templates/login_form.html
<form class="login_form" method="post" action="">
<div>Username: <input type="text" name="username" /></div>
<div>Password: <input type="password" name="password" /></div>
<div><input type="submit" value="Login" name="Login" /></div>
</form>
<div>You can use username "User1" or "User2" and password "qwerty" to login in system</div>
<hr />Step 2. CSS
Here are used CSS styles.
templates/css/styles.css
.login_form {
border: 1px solid #AAA;
padding:10px;
}
h3 {margin-top:3px;}
.chat_main {
border:1px solid #AAA;
-moz-box-shadow:0 0 10px #ccc;
-webkit-box-shadow: 0 0 10px #ccc;
width:350px;
padding:10px;
background:#f3f3f3;
}
.message {
border:1px solid #AAA;
margin:4px;
padding:5px;
-moz-border-radius:7px;
-webkit-border-radius:7px;
background:#ffffff;
}
.textf {-moz-box-shadow:0 0 10px #CCCCCC;
-webkit-box-shadow:0 0 10px #CCCCCC;
border:1px solid #CCCCCC;
height:40px;}
.submit {
-moz-border-radius:7px;
-webkit-border-radius:7px;
background:#F3F3F3;
border:1px solid #CCCCCC;
font-size:16px;
font-weight:bold;
height:35px;
margin-left:10px;
padding:5px;
}
.message span {
font-size:10px;
color:#888;
margin-left:10px;
}
.submit_form {
margin:10px 0px;
}Step 3. SQL
We will need to execute next SQL in our database.
CREATE TABLE `s_ajax_chat_messages` ( `id` INT( 11 ) NOT NULL AUTO_INCREMENT , `member_id` INT( 11 ) NOT NULL , `member_name` VARCHAR( 255 ) NOT NULL , `message` VARCHAR( 255 ) NOT NULL , `when` INT( 11 ) NOT NULL , PRIMARY KEY ( `id` ) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; CREATE TABLE `s_members` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `pass` varchar(40) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; INSERT INTO `s_members` (`id`, `name`, `pass`) VALUES (NULL, 'User1', 'd8578edf8458ce06fbc5bb76a58c5ca4'), (NULL, 'User2', 'd8578edf8458ce06fbc5bb76a58c5ca4');
Step 4. JS
Here are few necessary JS files to our project.
js/main.js
$(function() {
getMessages = function() {
var self = this;
var _sRandom = Math.random();
$.getJSON('index.php?action=get_last_messages' + '&_r=' + _sRandom, function(data){
if(data.messages) {
$('.chat_main').html(data.messages);
}
// start it again;
setTimeout(function(){
getMessages();
}, 5000);
});
}
getMessages();
});
js/jquery-1.4.2.min.js
This classe are general – jQuery library. No need to give full code of that file here. It always available as a download package
Step 5. PHP
I hope that most code will easy for your understanding – each function have normal name and commented.
Ok, here are all used PHP files:
index.php
<?php
// set error reporting level
if (version_compare(phpversion(), "5.3.0", ">=") == 1)
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
error_reporting(E_ALL & ~E_NOTICE);
require_once('inc/db.inc.php');
require_once('inc/login.inc.php');
require_once('inc/ajx_chat.inc.php');
if ($_REQUEST['action'] == 'get_last_messages') {
$sChatMessages = $GLOBALS['AjaxChat']->getMessages(true);
require_once('inc/Services_JSON.php');
$oJson = new Services_JSON();
echo $oJson->encode(array('messages' => $sChatMessages));
exit;
}
// draw login box
echo $GLOBALS['oSimpleLoginSystem']->getLoginBox();
// draw exta necessary files
echo '<link type="text/css" rel="stylesheet" href="templates/css/styles.css" />';
echo '<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>';
echo '<script type="text/javascript" src="js/main.js"></script>';
// draw chat messages
$sChatMessages = $GLOBALS['AjaxChat']->getMessages();
// draw input form + accept inserted texts
$sChatInputForm = 'Need login before using';
if ($GLOBALS['bLoggedIn']) {
$sChatInputForm = $GLOBALS['AjaxChat']->getInputForm();
$GLOBALS['AjaxChat']->acceptMessages();
}
echo $sChatMessages . $sChatInputForm;
?>inc/ajx_chat.inc.php
This is our Chat class
<?php
/**
* Simple ajaxy chat class
*/
class SimpleAjaxyChat {
/**
* constructor
*/
function SimpleAjaxyChat() {}
/**
* Adding to DB table posted message
*/
function acceptMessages() {
$sUsername = $GLOBALS['aLMemInfo']['name'];
$iUserID = (int)$GLOBALS['aLMemInfo']['id'];
if($sUsername && isset($_POST['s_message']) && $_POST['s_message'] != '') {
$sMessage = $GLOBALS['MySQL']->process_db_input($_POST['s_message'], A_TAGS_STRIP);
if ($sMessage != '') {
$GLOBALS['MySQL']->res("INSERT INTO `s_ajax_chat_messages` SET `member_id`='{$iUserID}', `member_name`='{$sUsername}', `message`='{$sMessage}', `when`=UNIX_TIMESTAMP()");
}
}
}
/**
* Return input text form
*/
function getInputForm() {
ob_start();
require_once('templates/chat_input.html');
return ob_get_clean();
}
/**
* Return last 15 messages
*/
function getMessages($bOnlyMessages = false) {
$aMessages = $GLOBALS['MySQL']->getAll("SELECT `s_ajax_chat_messages`.*, `s_members`.`name`, UNIX_TIMESTAMP()-`s_ajax_chat_messages`.`when` AS 'diff' FROM `s_ajax_chat_messages` INNER JOIN `s_members` ON `s_members`.`id` = `s_ajax_chat_messages`.`member_id` ORDER BY `id` DESC LIMIT 15");
$sMessages = '';
// collecting list of messages
foreach ($aMessages as $iID => $aMessage) {
$sExStyles = $sExJS = '';
$iDiff = (int)$aMessage['diff'];
if ($iDiff < 7) {
$sExStyles = 'style="display:none;"';
$sExJS = "<script> $('#message_{$aMessage['id']}').slideToggle('slow'); </script>";
}
$sWhen = date("H:i:s", $aMessage['when']);
$sMessages .= '<div class="message" id="message_'.$aMessage['id'].'" '.$sExStyles.'>' . $aMessage['name'] . ': ' . $aMessage['message'] . '<span>(' . $sWhen . ')</span></div>' . $sExJS;
}
if ($bOnlyMessages) return $sMessages;
return '<h3>Ajaxy Chat</h3><div class="chat_main">' . $sMessages . '</div>';
}
}
$GLOBALS['AjaxChat'] = new SimpleAjaxyChat();
?>inc/db.inc.php, inc/login.inc.php, inc/Services_JSON.php
All these classes are general in nature and is large enough that we will not describe them here, but they are always available as a download package
View Live Demo of our sample
Conclusion
Today I told you how to create own simple and good ajaxy chat application based on PHP, MySQL, jQuery and JSON a little. You can use this material to create own scripts into your startups. Good luck!
| I am web developer with huge experience (in web languages and even in system languages). Also I am the founder of current website (and several another). I like to write blogs about web development/design. Feel free to Follow us on Twitter: tweetmeme_screen_name='AramisGC'; | If you Enjoyed our article don't forget to Share the love with your friends. |


Working Dude 100 Percent . Thanks alot
I tried it and found a problem
Found error in the file ‘C:\wamp\www\source_2\example7\inc\ajx_chat.inc.php’ at line 40.
Called ‘getAll’ function with erroneous argument #0.
This is strange, I can advice you to check your DB details, and, you can try to execute that SQL in your phpMyAdmin (that SQL I using in that place):
SELECT `s_ajax_chat_messages`.*, `s_members`.`name`, UNIX_TIMESTAMP()-`s_ajax_chat_messages`.`when` AS ‘diff’ FROM `s_ajax_chat_messages` INNER JOIN `s_members` ON `s_members`.`id` = `s_ajax_chat_messages`.`member_id` ORDER BY `id` DESC LIMIT 15