• HTML/CSS
  • jQuery
  • PHP
  • JS
  • AJAX
  • MySQL
  • Res
  • XSLT
  • Contact Us
  • HTML/CSS
    • Game Development →
      • HTML5 Game Development - Lesson 1
      • HTML5 Game Development - Lesson 2
      • HTML5 Game Development - Lesson 3
      • HTML5 Game Development - Lesson 4
      • HTML5 Game Development - Lesson 5
      • HTML5 Game Development - Lesson 6
      • HTML5 Game Development - Lesson 7
    • Menus →
      • CSS3 multilevel menu with transition and animation
      • Marble Style CSS3 Navigation Menu
      • Toggle CSS3 Bottom Navigation Bar
      • Accordian like CSS3 Onclick Vertical Navigation
      • Multilevel CSS3 Metal Navigation with icons
      • Click-action CSS3 Dropdown Menu with jQuery
      • Click action Multi-level CSS3 Dropdown Menu
      • CSS3 Animated Menu
      • CSS3/jQuery crossbrowser Drop-down menu with tabs
      • CSS3 Drop sliding list Menu #6
      • CSS3 Slideout Menu #5
      • CSS3 Dropdown Menu #4
      • CSS3 Dropdown Menu #3
      • CSS3 Dropdown Menu #2
      • Cool CSS3 Dropdown Menu
    • Templates →
      • Robo Splash Page Layout
      • 'Mono' HTML5 CSS3 Single Page Layout
      • HTML5/CSS3 single page layout - Art theme
      • Attractive HTML CSS Anime Theme Website Layout
      • HTML CSS website layout #4 - Gray theme
      • Dark and clean HTML CSS website layout
      • HTML5&CSS3 single page layout - Rock portal
      • E-Store HTML5 CSS3 Single Page Layout
      • Under Water Themed HTML5 & CSS3 single page Layout
      • HTML5 & CSS3 Single Page Web Layout
    • HTML5 tutorials →
      • HTML5 Canvas Slideshow
      • HTML5 canvas - Custom brush #2 (Bubble brush)
      • HTML5 canvas - Custom brush (BezierCurveBrush)
      • HTML5 Face Builder
      • Pure HTML5 file upload
      • HTML5 image crop tool
      • HTML5 animation - patterns with loops
      • HTML5 3D circle text with shadows
      • HTML5 canvas pixelate effect
      • Animated Moving Clouds using HTML5
      • Animated Fireplace in HTML5
      • 3D Animated Box HTML5 WebGL Photo Slideshow
      • Your Own Paint Program
      • Image Zoomer in HTML5 Canvas
      • Photo Array in WebGL
      • HTML5 Canvas Image Color Picker
      • HTML5 Image Effects App - Adding Horizontal Flip
      • Keyboard Sensitive 3D Twisted Images in WebGl
      • Animated 3D WebGL Demonstration
      • HTML5 Image Effects App - Adding Noise and Invert
      • HTML5 Canvas Image Effects App - Adding Blur
      • Attractive Presentation with HTML5
      • HTML5 Canvas App for Online Image Enhancements
      • Water Ripple effect using HTML5 canvas
      • Animated 3D canvas object in HTML5
    • CSS3 tutorials →
      • CSS3 Image Hover Effects
      • CSS3 Modal Popups
      • Isometric interactive interior guide
      • Analog Clock with Pure CSS3
      • CSS3 Optical Illusions
      • CSS3 Animated Photo Slider
      • CSS3 Christmas Tree with Snow
      • How to Create a Pure CSS3 Slideshow
      • CSS3 Drop Caps
      • Pure CSS3 Slider
      • Fantastic Animated Buttons using CSS3
      • How to Create a Pure CSS3 Animated Photo Gallery
      • Toggle CSS3 Bottom Navigation Bar
      • How to Generate Runtime Multi-columns with CSS3
      • Multiple backgrounds and Animation with CSS3
  • jQuery
    • Photo album with jQuery Fotorama
    • Photo album with jQuery Chop Slider
    • Cool Background Image Sliding effect with jQuery
    • jQuery Templates - Usage Practice
    • Photo Album with Galleriffic jQuery plugin
    • Fantastic Photo Album with TN3
    • Ajaxy Photo Gallery (jQuery) with Custom Images Sets
    • Rotating Slider with Easing Effects in jQuery
    • Animated jQuery Progressbar Plugin
    • Nice CSS3 Lightbox Gallery
    • Photo Album with Highslide
    • Using Flux Slider jQuery plugin
    • Ajaxy Chained Selects
    • Modern jQuery Pagination for Content
    • Your own jQuery Slider Plugin
    • Attractive Photo Gallery using SmartGallery
    • Animated Photo Gallery using jQuery (Slider Kit)
  • PHP
    • Powerful Chat System - Lesson 3
    • Powerful Chat System - Lesson 2
    • Powerful Chat System
    • Access Control with Bit Masks
    • Own XML/JSON/HTML API with PHP
    • Your Own Ajax Poll System
    • Diary style PHP Guestbook
    • Smooth Curve Graphs with PHP and GD
    • Your Own Commenting System from Scratch
    • Autocomplete with PHP, jQuery, MySQL and XML
    • Your Own 5 Stars Voting System
    • How to use Memcache with PHP
    • How to install APC on Linux
    • How to Use APC Caching with PHP
    • Watermark processing on images using PHP and GD
    • ID3 Tags Reader with PHP
    • Advance Level Login system with Logic captcha
    • Protection and Methodologies of Security Vulnerabilities
    • How to Resize images on Server Side
    • How to Protect any Site from Spam using Akismet
    • Phar - PHP archiving practice
  • JS
    • Form Validation with Javascript and PHP
    • Fullscreen Javascript Slide navigation
    • Photo Scrambler grid in javascript
    • Photo Slideshow (zoom fading) effect
    • Custom scrollbars - cross-browser solution
    • Flare Lens Effect
    • Own RSS Reader Using Google Feed API
    • Cross-browser Wave Effects
    • Cross-browser Supported Image Skew effect
  • Res
    • ← Infographic
      • The Evolution of Languages
    • ← jQuery plugin roundups
      • December 2011
      • November 2011
      • 10 fresh jQuery Tutorials
      • October 2011
      • September 2011
      • 10 fresh Ajax related jQuery plugins
      • August 2011
      • 10 Oven Fresh jQuery Plugins for UI
      • 10 Most creative jQuery plugins for tables
      • 10 Most Creative jQuery Navigation Plugins
      • 10 fresh jQuery plugins for working with forms and UI
      • 10 superb jQuery plugins for working with images
    • ← HTML5 stuff
      • HTML5 and Games
      • 10 Fresh HTML5 Tutorials
      • Fresh impressing WebGL demonstrations
      • Most impressing HTML5 with WebGL demonstrations
      • 10 Fresh & Impressive HTML5 Canvas (and WebGL) Examples
      • 10 Exceptional Examples of HTML5 Canvas and Applications
    • ← Mobile
      • How to start developing own applications for Android
      • 10 Fresh Android tutorials
      • 10 Attractive Tutorials for Developing iPhone Applications
      • 10 Attractive android tutorials for developers
      • 10 Fresh iPad Apps for Web Designers & Developers
      • 10 Fresh Android Apps for Web Designers & Developers
      • 10 Fresh iPhone Apps for Web Designers & Developers
      • Top 10 iPhone apps for working with graphics
    • 12 Unique Navigation Menu Designs For Your Inspiration
    • 15 Unique and Creative Layouts 2011
    • 12 Beautifully Creative Flash Websites of 2011
    • Fresh collection of Original Captchas
  • XSLT
    • Animated forums using XSLT and Ajaxy
    • Multilevel Menu using XSLT
    • Delicious bookmarks using XSLT transformation
    • XPath visually
    • Tags cloud using XSLT transformation
    • Youtube videos using XSLT transformation
  • Contact Us
KEEP IN TOUCH

How to Easily Make AJAX Style PHP Chat Application

May18
2010
5 Comments Written by admin

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:

  • Live “Ajaxy” Chat Demo
  • download in package

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

download in package


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!

About: admin:
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.
    Tweet
   
   
Written by: admin on May 18, 2010.
Last revised by: admin
on May 19, 2010.

Related Stuff You Will Love!

  1. How to Easily Make a PHP Chat Application
    How to Easily Make a PHP Chat Application
  2. Powerful Chat System
    Powerful Chat System
  3. Powerful Chat System – Lesson 2
    Powerful Chat System – Lesson 2
  4. Powerful Chat System – Lesson 3
    Powerful Chat System – Lesson 3
Posted in AJAX, jQuery, PHP - Tagged AJAX, chat application, chat system, free, jQuery, JSON AJAX Web Chat, php chat
SHARE THIS Twitter Facebook Delicious StumbleUpon E-mail
« How to Easily Make a PHP Chat Application
» Import RSS Feeds using jFeed (jQuery)

3 Comments

  1. Shakeel's GravatarShakeel
    May 6, 2011 at 11:32 am | Permalink

    Working Dude 100 Percent . Thanks alot

  2. Muhammad's GravatarMuhammad
    June 20, 2011 at 8:06 am | Permalink

    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.

  3. admin's Gravataradmin
    June 21, 2011 at 3:05 pm | Permalink

    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

  1. Tweets that mention How to Easily Make AJAX Style PHP Chat Application – Script tutorials -- Topsy.com on May 18, 2010 at 3:06 pm
  2. How to Easily Make AJAX Style PHP Chat Application – Script tutorials | Neorack Tutorials on May 18, 2010 at 3:06 pm

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

*

*

CAPTCHA Image
Refresh Image

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Popular Tutorials

  • How to create easy pagination with jQuery
  • Animated jQuery Progressbar Plugin
  • Pure HTML5 file upload
  • Creating a HTML5 & CSS3 Single Page Web Layout
  • HTML5 Game Development – Lesson 6
  • How to Create Animated Photo Gallery using jQuery (Slider Kit)
  • Developing Your First HTML5 Game – Lesson 1
  • How to Easily Make a PHP Chat Application

Tags

3d AJAX android animated animation app application applications apps canvas captcha chat system coding creating css css3 developers effect effects flash fresh gallery how-to html html5 image images iphone javascript jQuery layout menu navigation new photo PHP plugin plugins slideshow system tutorial tutorials webgl website xslt

Recent Tutorials

  • Infographic: The Evolution of Languages
  • 12 Unique Navigation Menu Designs For Your Inspiration
  • Form Validation with Javascript and PHP
  • 10 fresh jQuery plugins (january 2012)
  • Powerful Chat System – Lesson 3
  • Invoicera offer results
  • CSS3 Image Hover Effects
  • HTML5 Canvas Slideshow

Friends

  • X-Musics

Tutorials for Web Developers Copyright © 2009-2011 Script tutorials · All rights reserved