<?xml version="1.0" encoding="UTF-8"?> <rss
version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
><channel><title>Script Tutorials &#187; AJAX | Script Tutorials | Web development</title> <atom:link href="http://www.script-tutorials.com/category/ajax/feed/" rel="self" type="application/rss+xml" /><link>http://www.script-tutorials.com</link> <description>Tutorials for Web Developers</description> <lastBuildDate>Fri, 03 Feb 2012 06:07:51 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <item><title>Powerful Chat System &#8211; Lesson 3</title><link>http://www.script-tutorials.com/powerful-chat-system-lesson-3/</link> <comments>http://www.script-tutorials.com/powerful-chat-system-lesson-3/#comments</comments> <pubDate>Mon, 30 Jan 2012 17:01:39 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[HTML5]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[ajax chat]]></category> <category><![CDATA[chat]]></category> <category><![CDATA[chat system]]></category> <category><![CDATA[registration]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1396</guid> <description><![CDATA[Powerful Chat System &#8211; Lesson 3 Today we continue a series of articles on the creation of powerful chat system. Our third lesson will contain next elements: join form (with html5 validation). A long ago, I have already made similar validation. So you can refresh your memories if you like. Today I will publish updated [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/powerful-chat-system-lesson-2/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/221/thumb.png" alt="Powerful Chat System &#8211; Lesson 2" /> Powerful Chat System &#8211; Lesson 2</a></li><li> <a
href="http://www.script-tutorials.com/powerful-chat-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/218/thumb.png" alt="Powerful Chat System" /> Powerful Chat System</a></li><li> <a
href="http://www.script-tutorials.com/how-to-easily-make-ajax-style-php-chat-application/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to Easily Make AJAX Style PHP Chat Application" /> How to Easily Make AJAX Style PHP Chat Application</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Powerful Chat System" alt="Powerful Chat System" src="http://www.script-tutorials.com/demos/226/thumb.png"></div><p><strong>Powerful Chat System &#8211; Lesson 3</strong><br
/> <br
/>Today we continue a series of articles on the creation of powerful chat system. Our third lesson will contain next elements: join form (with html5 validation). A long ago, I have already made similar <a
target="_blank" href="http://www.script-tutorials.com/data-validation-html5/">validation</a>. So you can refresh your memories if you like.<br
/> <span
id="more-1396"></span></p><p>Today I will publish updated sources of our growing project (several files was modified, plus I expanded structure of database slightly). All project is well structured: system classes is in &#8216;classes&#8217; folder, stylesheets in &#8216;css&#8217; folder, template files in &#8216;templates&#8217; folder, and &#8211; new folder &#8216;js&#8217; for javascript files.</p><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - demo 226" href="http://www.script-tutorials.com/demos/226/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - package" href="http://www.script-tutorials.com/demos/226/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. SQL</h3><p>I have added new field into table of profiles where we will store its first names. So, please execute next SQL:</p><pre class="brush:sql">
ALTER TABLE `cs_profiles` ADD `first_name` varchar(255) NOT NULL default '' AFTER `name`;
</pre><h3>Step 2. HTML</h3><p>I have updated template with login form. As you can see &#8211; I have expanded this markup and added join form here:</p><h4>templates/logout_form.html</h4><pre class="brush:html">
&lt;div class=&quot;column&quot;&gt;
    &lt;h3&gt;Powerful Chat System Demonstration&lt;/h3&gt;
    &lt;p&gt;Our chat will contain next features: registration, main chat, profiles with avatars, ranking system, private messaging, custom rooms, moderation / administration and possible something else (in future).&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;column&quot;&gt;

    &lt;div class=&quot;tabs_container&quot;&gt;
        &lt;ul class=&quot;tabs&quot;&gt;
            &lt;li class=&quot;active&quot;&gt;&lt;h3&gt;Log In&lt;/h3&gt;&lt;/li&gt;
            &lt;li&gt;&lt;h3&gt;Join&lt;/h3&gt;&lt;/li&gt;
        &lt;/ul&gt;
    &lt;/div&gt;

    &lt;div class=&quot;nav_container&quot;&gt;
        &lt;form class=&quot;login_form&quot; action=&quot;index.php&quot; method=&quot;post&quot; id=&quot;1&quot;&gt;
            &lt;label&gt;Username:&lt;/label&gt;&lt;input type=&quot;text&quot; name=&quot;username&quot;&gt;
            &lt;label&gt;Password:&lt;/label&gt;&lt;input type=&quot;password&quot; name=&quot;password&quot;&gt;
            &lt;input type=&quot;submit&quot; name=&quot;Login&quot; value=&quot;Login&quot;&gt;
        &lt;/form&gt;
        &lt;form class=&quot;join_form&quot; action=&quot;index.php&quot; method=&quot;post&quot; id=&quot;2&quot; style=&quot;display: none;&quot;&gt;

            &lt;label&gt;Full name:&lt;/label&gt;
            &lt;input type=&quot;text&quot; id=&quot;username&quot; name=&quot;username&quot; placeholder=&quot;Your name&quot; maxlength=&quot;128&quot; title=&quot;Your name&quot; required&gt;

            &lt;label&gt;First name:&lt;/label&gt;
            &lt;input type=&quot;text&quot; id=&quot;firstname&quot; name=&quot;firstname&quot; placeholder=&quot;Your first name&quot; maxlength=&quot;128&quot; title=&quot;Your first name&quot;&gt;

            &lt;label&gt;Last name:&lt;/label&gt;
            &lt;input type=&quot;text&quot; id=&quot;lastname&quot; name=&quot;lastname&quot; placeholder=&quot;Your last name&quot; maxlength=&quot;128&quot; title=&quot;Your last name&quot;&gt;

            &lt;label&gt;Email:&lt;/label&gt;
            &lt;input type=&quot;text&quot; id=&quot;email&quot; name=&quot;email&quot; placeholder=&quot;Your email&quot; maxlength=&quot;128&quot; title=&quot;Format: *@gmail.com&quot; pattern=&quot;.*@gmail\.com&quot; required&gt;

            &lt;label&gt;Password:&lt;/label&gt;
            &lt;input type=&quot;text&quot; id=&quot;password&quot; name=&quot;password&quot; maxlength=&quot;128&quot; title=&quot;Password&quot; required&gt;

            &lt;label&gt;Repeat Password:&lt;/label&gt;
            &lt;input type=&quot;text&quot; id=&quot;password&quot; name=&quot;password&quot; maxlength=&quot;128&quot; title=&quot;Repeat password&quot; required oninput=&quot;checkpass(this)&quot;&gt;

            &lt;input type=&quot;submit&quot; name=&quot;Join&quot; value=&quot;Join&quot;&gt;
        &lt;/form&gt;
    &lt;/div&gt;

&lt;/div&gt;

&lt;script&gt;
$(document).ready(function(){
    $('.tabs li h3').click(function () {
      $('.tabs li').removeClass('active');
      $(this).parent().addClass('active');

      $('.nav_container form').hide();
      var index = $('.tabs li h3').index(this);
      $('.nav_container form').eq(index).show();
      return false;
    });
});

function checkpass(input) {
    if (input.value != document.getElementById('password').value) {
        input.setCustomValidity('Password must match.');
    } else {
        input.setCustomValidity('');
    }
}
&lt;/script&gt;
</pre><p>Please pay attention to HTML structure of join form, it contain several new attributes for html5 validation: placeholder, required and pattern. This is pretty interesting.</p><h3>Step 3. CSS</h3><p>This file has updated too</p><h4>css/main.css</h4><pre class="brush:html">
/* page layout */
*{
    margin:0;
    padding:0;
}
body {
    background-color:#eee;
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
}
header {
    background-color:#212121;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    position:relative;
    width:100%;
    z-index:100;
}
header h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}
header a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}
header .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

/* main styles */
.container {
    background-color: #222;
    color: #bbb;
    margin: 20px auto;
    overflow: hidden;
    padding: 20px;
    position: relative;
    width: 800px;
}
.container h2 {
    color: #fff;
    margin-bottom: 10px;
}
.column {
    float: left;
    width: 48%;
}
.column:first-child {
    margin-right: 4%;
}
.column &gt; * {
    color: #ddd;
    margin-bottom: 10px;
}

/* tabs section */
.tabs_container {
    margin: 0;
}
.tabs {
    overflow: hidden;
}
.tabs li {
    float: left;
    list-style: none;
}
.tabs li h3:first-child {
    margin-left: 10px
}
.tabs li h3 {
    border: 1px solid #ddd;
    border-bottom-width: 0;
    display: block;
    margin: 0 2px 0 0;
    padding: 6px 10px 4px
}
.tabs li.active h3 {
    background-color: #555;
    border: 1px solid #ddd;
    border-bottom-width: 0;

    -moz-border-radius: 4px 4px 0 0;
    -ms-border-radius: 4px 4px 0 0;
    -o-border-radius: 4px 4px 0 0;
    -webkit-border-radius: 4px 4px 0 0;
    border-radius: 4px 4px 0 0;
}
.tabs li h3:hover {
    background-color: #666;
    cursor: pointer;
}
.tabs li.active h3:hover {
    background-color: #555;
    cursor: normal;
}
.nav_container form {
    background-color: #555;
    display: block;
    padding: 15px;
}
.column h3 {
    color: #fff;
}
.login_form input,.login_form label,
.join_form input,.join_form label {
    display: block;
    margin-bottom: 10px;
}
input[type=text], input[type=password], input[type=submit] {
    -moz-border-radius: 5px;
    -ms-border-radius: 5px;
    -o-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
}
input[type=text], input[type=password] {
    font-size: 16px;
    height: 25px;
    margin-right: 10px;
    width: 200px;
}
input[type=submit]{
    cursor: pointer;
    font-size: 16px;
    font-weight: bold;
    height: 35px;
    padding: 5px;
}

/* chat block */
.chat_messages {
    border: 1px solid #888;
    box-shadow: 0 0 5px #AAA;
    color: #000;
    padding: 10px;
}
.chat_messages h2 {
    color: #fff;
}
.chat_messages .message {
    background-color: #fff;
    margin: 5px;
    padding: 5px;

    -moz-border-radius: 5px;
    -ms-border-radius: 5px;
    -o-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
}
.chat_messages .message span {
    color: #444;
    font-size: 10px;
    margin-left: 10px;
}
.chat_submit_form {
    margin: 10px 0px;
}
.chat_submit_form div {
    float: left;
    width: 49%;
}
.chat_submit_form .error, .chat_submit_form .success, .chat_submit_form .protect {
    display: none;
}
.chat_submit_form .error {
    color: #f55;
}
.chat_submit_form .success {
    color: #5f5;
}
.chat_submit_form .protect {
    color: #55f;
}
</pre><h3>Step 4. PHP</h3><p>Now, lets review php sources. Our index.php file has updated. I have added here join processing functional. Before actual joining, we have to check if someone else was joined with same email (this field should be unique of course)</p><h4>index.php</h4><pre class="brush:php">
&lt;?php

// set error reporting level
if (version_compare(phpversion(), '5.3.0', '&gt;=') == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE);

require_once('classes/Services_JSON.php');
require_once('classes/CMySQL.php'); // including service class to work with database
require_once('classes/CLogin.php'); // including service class to work with login processing

$sErrors = '';
// join processing
if (! isset($_SESSION['member_id']) &amp;&amp; $_POST['Join'] == 'Join') {
    $sUsername = $GLOBALS['MySQL']-&gt;escape($_POST['username']);
    $sFirstname = $GLOBALS['MySQL']-&gt;escape($_POST['firstname']);
    $sLastname = $GLOBALS['MySQL']-&gt;escape($_POST['lastname']);
    $sEmail = $GLOBALS['MySQL']-&gt;escape($_POST['email']);
    $sPassword = $GLOBALS['MySQL']-&gt;escape($_POST['password']);

    if ($sUsername &amp;&amp; $sEmail &amp;&amp; $sPassword) {
        // check if already exist
        $aProfile = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `cs_profiles` WHERE `email`='{$sEmail}'&quot;);
        if ($aProfile['id'] &gt; 0) {
            $sErrors = '&lt;h2&gt;Another profile with same email already exist&lt;/h2&gt;';
        } else {
            // generate Salt and Cached password
            $sSalt = 'testing'; // TODO - we will add generation of salt in future
            $sPass = sha1(md5($sPassword) . $sSalt);

            // add new member into database
            $sSQL = &quot;
                INSERT INTO `cs_profiles` SET
                `name` = '{$sUsername}',
                `first_name` = '{$sFirstname}',
                `last_name` = '{$sLastname}',
                `email` = '{$sEmail}',
                `password` = '{$sPass}',
                `salt` = '{$sSalt}',
                `status` = 'active',
                `role` = '1',
                `date_reg` = NOW();
            &quot;;
            $GLOBALS['MySQL']-&gt;res($sSQL);

            // autologin
            $GLOBALS['CLogin']-&gt;performLogin($sUsername, $sPassword);
        }
    }
}

// login system init and generation code
$sLoginForm = $GLOBALS['CLogin']-&gt;getLoginBox();

$sChat = '&lt;h2&gt;You do not have rights to use chat&lt;/h2&gt;';
$sInput = '';
if ($_SESSION['member_id'] &amp;&amp; $_SESSION['member_status'] == 'active' &amp;&amp; $_SESSION['member_role']) {
    require_once('classes/CChat.php'); // including service class to work with chat

    // get last messages
    $sChat = $GLOBALS['MainChat']-&gt;getMessages();
    if ($_GET['action'] == 'get_last_messages') { // regular updating of messages in chat
        $oJson = new Services_JSON();
        header('Content-type: application/json');
        echo $oJson-&gt;encode(array('messages' =&gt; $sChat));
        exit;
    }

    // get input form
    $sInput = $GLOBALS['MainChat']-&gt;getInputForm();

    if ($_POST['message']) { // POST-ing of message
        $iRes = $GLOBALS['MainChat']-&gt;acceptMessage();

        $oJson = new Services_JSON();
        header('Content-type: application/json');
        echo $oJson-&gt;encode(array('result' =&gt; $iRes));
        exit;
    }
}

// draw common page
echo strtr(file_get_contents('templates/main_page.html'), array('{form}' =&gt; $sLoginForm . $sErrors, '{chat}' =&gt; $sChat, '{input}' =&gt; $sInput));
</pre><p>As you can see &#8211; I have added chat functionality today.</p><h4>classes/CLogin.php</h4><pre class="brush:php">
&lt;?php

class CLogin {

    // constructor
    function CLogin() {
        session_start();
    }

    // get login box function
    function getLoginBox() {
        if (isset($_GET['logout'])) { // logout processing
            if (isset($_SESSION['member_name']) &amp;&amp; isset($_SESSION['member_pass']))
                $this-&gt;performLogout();
        }

        if ($_POST &amp;&amp; $_POST['Login'] == 'Login' &amp;&amp; $_POST['username'] &amp;&amp; $_POST['password']) { // login processing
            if ($this-&gt;checkLogin($_POST['username'], $_POST['password'], false)) { // successful login
                $this-&gt;performLogin($_POST['username'], $_POST['password']);
                header( &quot;Location:{$_SERVER['REQUEST_URI']}&quot; );
                exit;
            } else { // wrong login
                return file_get_contents('templates/login_form.html') . '&lt;h2&gt;Username or Password is incorrect&lt;/h2&gt;';
            }
        } else { // in case if we already logged (on refresh page):
            if (isset($_SESSION['member_name']) &amp;&amp; $_SESSION['member_name'] &amp;&amp; $_SESSION['member_pass']) {
                $aReplaces = array(
                    '{name}' =&gt; $_SESSION['member_name'],
                    '{status}' =&gt; $_SESSION['member_status'],
                    '{role}' =&gt; $_SESSION['member_role'],
                );
                return strtr(file_get_contents('templates/logout_form.html'), $aReplaces);
            }

            // otherwise - draw login form
            return file_get_contents('templates/login_form.html');
        }
    }

    // perform login
    function performLogin($sName, $sPass) {
        $this-&gt;performLogout();

        // make variables safe
        $sName = $GLOBALS['MySQL']-&gt;escape($sName);

        $aProfile = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `cs_profiles` WHERE `name`='{$sName}'&quot;);
        // $sPassEn = $aProfile['password'];
        $iPid = $aProfile['id'];
        $sSalt = $aProfile['salt'];
        $sStatus = $aProfile['status'];
        $sRole = $aProfile['role'];

        $sPass = sha1(md5($sPass) . $sSalt);

        $_SESSION['member_id'] = $iPid;
        $_SESSION['member_name'] = $sName;
        $_SESSION['member_pass'] = $sPass;
        $_SESSION['member_status'] = $sStatus;
        $_SESSION['member_role'] = $sRole;
    }

    // perform logout
    function performLogout() {
        unset($_SESSION['member_id']);
        unset($_SESSION['member_name']);
        unset($_SESSION['member_pass']);
        unset($_SESSION['member_status']);
        unset($_SESSION['member_role']);
    }

    // check login
    function checkLogin($sName, $sPass, $isHash = true) {
        // make variables safe
        $sName = $GLOBALS['MySQL']-&gt;escape($sName);
        $sPass = $GLOBALS['MySQL']-&gt;escape($sPass);

        $aProfile = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `cs_profiles` WHERE `name`='{$sName}'&quot;);
        $sPassEn = $aProfile['password'];

        if ($sName &amp;&amp; $sPass &amp;&amp; $sPassEn) {
            if (! $isHash) {
                $sSalt = $aProfile['salt'];
                $sPass = sha1(md5($sPass) . $sSalt);
            }
            return ($sPass == $sPassEn);
        }
        return false;
    }
}

$GLOBALS['CLogin'] = new CLogin();
</pre><p>Minor changes were made in this file too. The rest of the functional was not changed. We will continue enhance our chat soon.</p><hr
/><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - demo 226" href="http://www.script-tutorials.com/demos/226/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - package" href="http://www.script-tutorials.com/demos/226/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>I hope that our new series of articles of chat system creation is useful and interesting for you. If you want to share your ideas, or you noticed any weakness &#8211; don&#8217;t hesitate to contact us. Good luck and welcome back!</p><div
class="shr-publisher-1396"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/powerful-chat-system-lesson-2/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/221/thumb.png" alt="Powerful Chat System &#8211; Lesson 2" /> <br
/> Powerful Chat System &#8211; Lesson 2</a></li><li> <a
href="http://www.script-tutorials.com/powerful-chat-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/218/thumb.png" alt="Powerful Chat System" /> <br
/> Powerful Chat System</a></li><li> <a
href="http://www.script-tutorials.com/how-to-easily-make-ajax-style-php-chat-application/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to Easily Make AJAX Style PHP Chat Application" /> <br
/> How to Easily Make AJAX Style PHP Chat Application</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/powerful-chat-system-lesson-3/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Powerful Chat System &#8211; Lesson 2</title><link>http://www.script-tutorials.com/powerful-chat-system-lesson-2/</link> <comments>http://www.script-tutorials.com/powerful-chat-system-lesson-2/#comments</comments> <pubDate>Wed, 18 Jan 2012 17:17:45 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[ajax chat]]></category> <category><![CDATA[chat]]></category> <category><![CDATA[chat system]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1373</guid> <description><![CDATA[Powerful Chat System &#8211; Lesson 2 Today we continue a series of articles on the creation of powerful chat system. Our second lesson will contain next elements: smart chat (ajax, with spam filtering &#8211; protection from the frequent messages). I have decided to make registration for next lesson. Hope that it is ok for you. [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/powerful-chat-system-lesson-3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/226/thumb.png" alt="Powerful Chat System &#8211; Lesson 3" /> Powerful Chat System &#8211; Lesson 3</a></li><li> <a
href="http://www.script-tutorials.com/powerful-chat-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/218/thumb.png" alt="Powerful Chat System" /> Powerful Chat System</a></li><li> <a
href="http://www.script-tutorials.com/how-to-easily-make-ajax-style-php-chat-application/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to Easily Make AJAX Style PHP Chat Application" /> How to Easily Make AJAX Style PHP Chat Application</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Powerful Chat System" alt="Powerful Chat System" src="http://www.script-tutorials.com/demos/221/thumb.png"></div><p><strong>Powerful Chat System &#8211; Lesson 2</strong><br
/> <br
/>Today we continue a series of articles on the creation of powerful chat system. Our second lesson will contain next elements: smart chat (ajax, with spam filtering &#8211; protection from the frequent messages). I have decided to make registration for next lesson. Hope that it is ok for you.<br
/> <span
id="more-1373"></span></p><p>Today I have included next elements: chat processor, plus &#8211; slight corrections in our previous sources. All project is well structured: system classes is in &#8216;classes&#8217; folder, stylesheets in &#8216;css&#8217; folder, template files in &#8216;templates&#8217; folder, and &#8211; new folder &#8216;js&#8217; for javascript files.</p><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - demo 221" href="http://www.script-tutorials.com/demos/221/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - package" href="http://www.script-tutorials.com/demos/221/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. SQL</h3><p>This table has got minor changes. I have changed type of field &#8216;when&#8217;.</p><pre class="brush:sql">
CREATE TABLE `cs_messages` (
  `id` int(11) unsigned NOT NULL auto_increment,
  `sender` int(11) unsigned NOT NULL,
  `recipient` int(11) unsigned NOT NULL default '0',
  `message` VARCHAR(255) NOT NULL,
  `when` int(11) NOT NULL default '0',
  `room` int(5) unsigned NOT NULL default '0',
  `type` tinyint(1) unsigned NOT NULL default '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</pre><h3>Step 2. HTML</h3><p>This is main (index) page html markup:</p><h4>templates/main_page.html</h4><pre class="brush:html">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
&lt;head&gt;
    &lt;title&gt;Powerful Chat System - Lesson 2&lt;/title&gt;
    &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
    &lt;script src=&quot;http://code.jquery.com/jquery-latest.min.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;header&gt;
        &lt;h2&gt;Powerful Chat System - Lesson 2&lt;/h2&gt;
        &lt;a href=&quot;http://www.script-tutorials.com/powerful-chat-system-lesson-2/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
    &lt;/header&gt;
    &lt;div class=&quot;container&quot;&gt;
        {form}
    &lt;/div&gt;
    &lt;div class=&quot;container&quot;&gt;
        &lt;h2&gt;Main Chat Block&lt;/h2&gt;
        &lt;div class=&quot;chat_messages&quot;&gt;
            {chat}
        &lt;/div&gt;
        {input}
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><p>As you can see &#8211; I have changed our second container (which contains our ajax chat).</p><h4>templates/login_form.html and templates/logout_form.html</h4><p>These files haven&#8217;t changed since last time. Next one new template &#8211; chat form:</p><h4>templates/chat.html</h4><pre class="brush:html">
&lt;form class=&quot;chat_submit_form&quot;&gt;
    &lt;div&gt;&lt;input type=&quot;text&quot; name=&quot;message&quot; /&gt;&lt;input type=&quot;submit&quot; value=&quot;Submit&quot; name=&quot;Submit&quot; /&gt;&lt;/div&gt;
    &lt;div&gt;
        &lt;h3 class=&quot;error&quot;&gt;Some error occurs during sending message&lt;/h3&gt;
        &lt;h3 class=&quot;success&quot;&gt;Message successfully sent&lt;/h3&gt;
        &lt;h3 class=&quot;protect&quot;&gt;Please wait 5 secs before adding next message&lt;/h3&gt;
    &lt;/div&gt;
&lt;/form&gt;
&lt;script src=&quot;js/chat.js&quot;&gt;&lt;/script&gt;
</pre><h3>Step 3. CSS</h3><p>This file contains updated styles of our chat</p><h4>css/main.css</h4><pre class="brush:html">
/* page layout */
*{
    margin:0;
    padding:0;
}
body {
    background-color:#eee;
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
}
header {
    background-color:#212121;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    position:relative;
    width:100%;
    z-index:100;
}
header h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}
header a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}
header .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

/* main styles */
.container {
    background-color: #222;
    color: #bbb;
    margin: 20px auto;
    overflow: hidden;
    padding: 20px;
    position: relative;
    width: 800px;
}
.container h2 {
    color: #fff;
    margin-bottom: 10px;
}
.column {
    float: left;
    width: 48%;
}
.column:first-child {
    margin-right: 4%;
}
.column &gt; * {
    color: #ddd;
    margin-bottom: 10px;
}
.column h3 {
    color: #fff;
}
.login_form input,.login_form label {
    display: block;
    margin-bottom: 10px;
}
input[type=text], input[type=password], input[type=submit] {
    -moz-border-radius: 5px;
    -ms-border-radius: 5px;
    -o-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
}
input[type=text], input[type=password] {
    font-size: 16px;
    height: 30px;
    margin-right: 10px;
    width: 200px;
}
input[type=submit]{
    cursor: pointer;
    font-size: 16px;
    font-weight: bold;
    height: 35px;
    padding: 5px;
}

/* chat block */
.chat_messages {
    border: 1px solid #888;
    box-shadow: 0 0 5px #AAA;
    color: #000;
    padding: 10px;
}
.chat_messages h2 {
    color: #fff;
}
.chat_messages .message {
    background-color: #fff;
    margin: 5px;
    padding: 5px;

    -moz-border-radius: 5px;
    -ms-border-radius: 5px;
    -o-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
}
.chat_messages .message span {
    color: #444;
    font-size: 10px;
    margin-left: 10px;
}
.chat_submit_form {
    margin: 10px 0px;
}
.chat_submit_form div {
    float: left;
    width: 49%;
}
.chat_submit_form .error, .chat_submit_form .success, .chat_submit_form .protect {
    display: none;
}
.chat_submit_form .error {
    color: #f55;
}
.chat_submit_form .success {
    color: #5f5;
}
.chat_submit_form .protect {
    color: #55f;
}
</pre><h3>Step 4. JS</h3><p>I have created first JS for our chat. At beginning &#8211; it contain one function for regular obtaining messages, and handler of form submitting.</p><h4>js/chat.js</h4><pre class="brush:js">
$(function() {
    getMessages = function() {
        $.getJSON('index.php?action=get_last_messages', function(data){
            if (data.messages) {
                $('.chat_messages').html(data.messages);
            }

            // get recent chat messages in loop
            setTimeout(function(){
               getMessages();
            }, 5000);
        });
    }
    getMessages();

    $('.chat_submit_form').submit(function() {
        $.post('index.php', { message: $('.chat_submit_form input[name=message]').val() },
            function(data){
                if (data.result == 1) {
                    $('.chat_submit_form .success').fadeIn('slow', function () {
                        $(this).delay(1000).fadeOut('slow');
                    });
                } else if (data.result == 2) {
                    $('.chat_submit_form .protect').fadeIn('slow', function () {
                        $(this).delay(1000).fadeOut('slow');
                    });
                } else {
                    $('.chat_submit_form .error').fadeIn('slow', function () {
                        $(this).delay(1000).fadeOut('slow');
                    });
                }
            }
        );
        return false;
    });
});
</pre><h3>Step 5. PHP</h3><p>Now, lets review php sources:</p><h4>index.php</h4><pre class="brush:php">
&lt;?php

// set error reporting level
if (version_compare(phpversion(), '5.3.0', '&gt;=') == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE);

require_once('classes/Services_JSON.php');
require_once('classes/CMySQL.php'); // including service class to work with database
require_once('classes/CLogin.php'); // including service class to work with login processing

// login system init and generation code
$sLoginForm = $GLOBALS['CLogin']-&gt;getLoginBox();

$sChat = '&lt;h2&gt;You do not have rights to use chat&lt;/h2&gt;';
$sInput = '';
if ($_SESSION['member_id'] &amp;&amp; $_SESSION['member_status'] == 'active' &amp;&amp; $_SESSION['member_role']) {
    require_once('classes/CChat.php'); // including service class to work with chat

    // get last messages
    $sChat = $GLOBALS['MainChat']-&gt;getMessages();
    if ($_GET['action'] == 'get_last_messages') { // regular updating of messages in chat
        $oJson = new Services_JSON();
        header('Content-type: application/json');
        echo $oJson-&gt;encode(array('messages' =&gt; $sChat));
        exit;
    }

    // get input form
    $sInput = $GLOBALS['MainChat']-&gt;getInputForm();

    if ($_POST['message']) { // POST-ing of message
        $iRes = $GLOBALS['MainChat']-&gt;acceptMessage();

        $oJson = new Services_JSON();
        header('Content-type: application/json');
        echo $oJson-&gt;encode(array('result' =&gt; $iRes));
        exit;
    }
}

// draw common page
echo strtr(file_get_contents('templates/main_page.html'), array('{form}' =&gt; $sLoginForm, '{chat}' =&gt; $sChat, '{input}' =&gt; $sInput));
</pre><p>As you can see &#8211; I have added chat functionality today.</p><h4>classes/CLogin.php</h4><pre class="brush:php">
&lt;?php

class CLogin {

    // constructor
    function CLogin() {
        session_start();
    }

    // get login box function
    function getLoginBox() {
        if (isset($_GET['logout'])) { // logout processing
            if (isset($_SESSION['member_name']) &amp;&amp; isset($_SESSION['member_pass']))
                $this-&gt;performLogout();
        }

        if ($_POST &amp;&amp; $_POST['username'] &amp;&amp; $_POST['password']) { // login processing
            if ($this-&gt;checkLogin($_POST['username'], $_POST['password'], false)) { // successful login
                $this-&gt;performLogin($_POST['username'], $_POST['password']);
                header( &quot;Location:{$_SERVER['REQUEST_URI']}&quot; );
                exit;
            } else { // wrong login
                return file_get_contents('templates/login_form.html') . '&lt;h2&gt;Username or Password is incorrect&lt;/h2&gt;';
            }
        } else { // in case if we already logged (on refresh page):
            if (isset($_SESSION['member_name']) &amp;&amp; $_SESSION['member_name'] &amp;&amp; $_SESSION['member_pass']) {
                $aReplaces = array(
                    '{name}' =&gt; $_SESSION['member_name'],
                    '{status}' =&gt; $_SESSION['member_status'],
                    '{role}' =&gt; $_SESSION['member_role'],
                );
                return strtr(file_get_contents('templates/logout_form.html'), $aReplaces);
            }

            // otherwise - draw login form
            return file_get_contents('templates/login_form.html');
        }
    }

    // perform login
    function performLogin($sName, $sPass) {
        $this-&gt;performLogout();

        // make variables safe
        $sName = $GLOBALS['MySQL']-&gt;escape($sName);

        $aProfile = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `cs_profiles` WHERE `name`='{$sName}'&quot;);
        // $sPassEn = $aProfile['password'];
        $iPid = $aProfile['id'];
        $sSalt = $aProfile['salt'];
        $sStatus = $aProfile['status'];
        $sRole = $aProfile['role'];

        $sPass = sha1(md5($sPass) . $sSalt);

        $_SESSION['member_id'] = $iPid;
        $_SESSION['member_name'] = $sName;
        $_SESSION['member_pass'] = $sPass;
        $_SESSION['member_status'] = $sStatus;
        $_SESSION['member_role'] = $sRole;
    }

    // perform logout
    function performLogout() {
        unset($_SESSION['member_id']);
        unset($_SESSION['member_name']);
        unset($_SESSION['member_pass']);
        unset($_SESSION['member_status']);
        unset($_SESSION['member_role']);
    }

    // check login
    function checkLogin($sName, $sPass, $isHash = true) {
        // make variables safe
        $sName = $GLOBALS['MySQL']-&gt;escape($sName);
        $sPass = $GLOBALS['MySQL']-&gt;escape($sPass);

        $aProfile = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `cs_profiles` WHERE `name`='{$sName}'&quot;);
        $sPassEn = $aProfile['password'];

        if ($sName &amp;&amp; $sPass &amp;&amp; $sPassEn) {
            if (! $isHash) {
                $sSalt = $aProfile['salt'];
                $sPass = sha1(md5($sPass) . $sSalt);
            }
            return ($sPass == $sPassEn);
        }
        return false;
    }
}

$GLOBALS['CLogin'] = new CLogin();
</pre><p>This class is updated too. I have decided to add &#8216;member_id&#8217; in sessions too. It will useful afterward.</p><h4>classes/CMySQL.php</h4><p>This is database service class. Available in package. Pay attention &#8211; database settings of our project is in this file.</p><h4>classes/Services_JSON.php</h4><p>This is JSON service class. Available in package.</p><h4>classes/CChat.php</h4><pre class="brush:php">
&lt;?php

class CChat {

    // constructor
    function CChat() {}

    // add to DB message
    function acceptMessage() {
        $sName = $GLOBALS['MySQL']-&gt;escape($_SESSION['member_name']);
        $iPid = (int)$_SESSION['member_id'];
        $sMessage = $GLOBALS['MySQL']-&gt;escape($_POST['message']);

        if ($iPid &amp;&amp; $sName != '' &amp;&amp; $sMessage != '') {
            $sSQL = &quot;
                SELECT `id`
                FROM `cs_messages`
                WHERE `sender` = '{$iPid}' AND UNIX_TIMESTAMP( ) - `when` &lt; 5
                LIMIT 1
            &quot;;
            $iLastId = $GLOBALS['MySQL']-&gt;getOne($sSQL);
            if ($iLastId) return 2; // as protection from very often messages

            $bRes = $GLOBALS['MySQL']-&gt;res(&quot;INSERT INTO `cs_messages` SET `sender` = '{$iPid}', `message` = '{$sMessage}', `when` = UNIX_TIMESTAMP()&quot;);
            return ($bRes) ? 1 : 3;
        }
    }

    // return input text form
    function getInputForm() {
        return file_get_contents('templates/chat.html');
    }

    // get last 10 messages
    function getMessages() {
        $sSQL = &quot;
            SELECT `a` . * , `cs_profiles`.`name` , UNIX_TIMESTAMP( ) - `a`.`when` AS 'diff'
            FROM `cs_messages` AS `a`
            INNER JOIN `cs_profiles` ON `cs_profiles`.`id` = `a`.`sender`
            ORDER BY `a`.`id` DESC
            LIMIT 10
        &quot;;
        $aMessages = $GLOBALS['MySQL']-&gt;getAll($sSQL);
        asort($aMessages);

        // create list of messages
        $sMessages = '';
        foreach ($aMessages as $i =&gt; $aMessage) {
            $sExStyles = $sExJS = '';
            $iDiff = (int)$aMessage['diff'];
            if ($iDiff &lt; 7) { // less than 7 seconds
                $sExStyles = 'style=&quot;display:none;&quot;';
                $sExJS = &quot;&lt;script&gt; $('#message_{$aMessage['id']}').fadeIn('slow'); &lt;/script&gt;&quot;;
            }

            $sWhen = date(&quot;H:i:s&quot;, $aMessage['when']);
            $sMessages .= '&lt;div class=&quot;message&quot; id=&quot;message_'.$aMessage['id'].'&quot; '.$sExStyles.'&gt;&lt;b&gt;' . $aMessage['name'] . ':&lt;/b&gt; ' . $aMessage['message'] . '&lt;span&gt;(' . $sWhen . ')&lt;/span&gt;&lt;/div&gt;' . $sExJS;
        }
        return $sMessages;
    }
}

$GLOBALS['MainChat'] = new CChat();
</pre><p>This is our new class for chat processor. For now &#8211; it contain only 3 functions: acceptMessage, getInputForm and getMessages.</p><hr
/><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - demo 221" href="http://www.script-tutorials.com/demos/221/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - package" href="http://www.script-tutorials.com/demos/221/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>I will hope that our new series of articles of chat system creation will be useful and interesting for you. If you want to share your ideas, or you noticed any weakness &#8211; don&#8217;t hesitate to contact us. Good luck and welcome back!</p><div
class="shr-publisher-1373"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/powerful-chat-system-lesson-3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/226/thumb.png" alt="Powerful Chat System &#8211; Lesson 3" /> <br
/> Powerful Chat System &#8211; Lesson 3</a></li><li> <a
href="http://www.script-tutorials.com/powerful-chat-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/218/thumb.png" alt="Powerful Chat System" /> <br
/> Powerful Chat System</a></li><li> <a
href="http://www.script-tutorials.com/how-to-easily-make-ajax-style-php-chat-application/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to Easily Make AJAX Style PHP Chat Application" /> <br
/> How to Easily Make AJAX Style PHP Chat Application</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/powerful-chat-system-lesson-2/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Powerful Chat System</title><link>http://www.script-tutorials.com/powerful-chat-system/</link> <comments>http://www.script-tutorials.com/powerful-chat-system/#comments</comments> <pubDate>Fri, 13 Jan 2012 14:14:57 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[ajax chat]]></category> <category><![CDATA[chat]]></category> <category><![CDATA[chat system]]></category> <category><![CDATA[profiles]]></category> <category><![CDATA[registration]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1360</guid> <description><![CDATA[Powerful Chat System Today we begin a series of articles on the creation of powerful chat system. The system will contain next elements: registration, login processing, main chat, profiles with avatars, ranking system (of profiles), private messaging, custom rooms, moderation / administration and possible something else (in future). This will be ajax chat PHP) with [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/powerful-chat-system-lesson-3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/226/thumb.png" alt="Powerful Chat System &#8211; Lesson 3" /> Powerful Chat System &#8211; Lesson 3</a></li><li> <a
href="http://www.script-tutorials.com/powerful-chat-system-lesson-2/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/221/thumb.png" alt="Powerful Chat System &#8211; Lesson 2" /> Powerful Chat System &#8211; Lesson 2</a></li><li> <a
href="http://www.script-tutorials.com/how-to-easily-make-a-php-chat-application/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to Easily Make a PHP Chat Application" /> How to Easily Make a PHP Chat Application</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Powerful Chat System" alt="Powerful Chat System" src="http://www.script-tutorials.com/demos/218/thumb.png"></div><p><strong>Powerful Chat System</strong><br
/> <br
/>Today we begin a series of articles on the creation of powerful chat system. The system will contain next elements: registration, login processing, main chat, profiles with avatars, ranking system (of profiles), private messaging, custom rooms, moderation / administration and possible something else (in future). This will be ajax chat PHP) with storing messages in database (MySQL). Plus we will implement CSS3/HTML5 features in our development process.<br
/> <span
id="more-1360"></span></p><p>Today I have included next elements: initial code (PHP + SQL) with login processor. All project will be well structured: system classes is in &#8216;classes&#8217; folder, stylesheets in &#8216;css&#8217; folder, template files in &#8216;templates&#8217; folder.</p><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - demo 218" href="http://www.script-tutorials.com/demos/218/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - package" href="http://www.script-tutorials.com/demos/218/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. SQL</h3><p>Here is SQL structure of tables for profiles and messages</p><pre class="brush:sql">
CREATE TABLE `cs_profiles` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `name` varchar(255) NOT NULL default '',
  `last_name` varchar(255) NOT NULL default '',
  `email` varchar(255) NOT NULL default '',
  `password` varchar(40) NOT NULL default '',
  `salt` varchar(10) NOT NULL default '',
  `status` enum('active','passive') NOT NULL default 'active',
  `role` tinyint(4) unsigned NOT NULL default '1',
  `about` varchar(255) NOT NULL,
  `date_reg` datetime NOT NULL default '0000-00-00 00:00:00',
  `rate` float NOT NULL,
  `rate_count` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

INSERT INTO `cs_profiles` (`name`, `last_name`, `email`, `password`, `salt`, `status`, `role`, `about`, `date_reg`, `rate`, `rate_count`) VALUES
('test user', 'test user last name', 'user@user.com', 'b88c654d6c68fc37f4dda1d29935235eea9a845b', 'testing', 'active', 1, 'Few words about test user', '2012-01-14 00:00:00', 0, 0),
('moderator', 'moderator last name', 'moderator@moderator.com', 'b88c654d6c68fc37f4dda1d29935235eea9a845b', 'testing', 'active', 4, 'Few words about moderator', '2012-01-14 00:00:00', 0, 0),
('admin', 'admin last name', 'admin@admin.com', 'b88c654d6c68fc37f4dda1d29935235eea9a845b', 'testing', 'active', 5, 'Few words about admin', '2012-01-14 00:00:00', 0, 0);

CREATE TABLE `cs_messages` (
  `id` int(11) unsigned NOT NULL auto_increment,
  `sender` int(11) unsigned NOT NULL,
  `recipient` int(11) unsigned NOT NULL default '0',
  `message` VARCHAR(255) NOT NULL,
  `when` TIMESTAMP NOT NULL default CURRENT_TIMESTAMP,
  `room` int(5) unsigned NOT NULL default '0',
  `type` tinyint(1) unsigned NOT NULL default '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</pre><p>I have added 3 profiles in the system. Each of them have different role. I plan to make ordinary members (1), moderators (4), administrators (5). You can use another roles (as example 2 and 3) for any other purposes (paid members?). And, quite forgot &#8211; password for all of them is <b>&#8216;password&#8217;</b>. So you can login as &#8216;test user&#8217; -> &#8216;password&#8217;, &#8216;moderator&#8217; -> &#8216;password&#8217; and &#8216;admin&#8217; -> &#8216;password&#8217;. Registration process will in next article.</p><h3>Step 2. HTML</h3><p>This is main (index) page html markup:</p><h4>templates/main_page.html</h4><pre class="brush:html">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
&lt;head&gt;
    &lt;title&gt;Powerful Chat System&lt;/title&gt;
    &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;header&gt;
        &lt;h2&gt;Powerful Chat System&lt;/h2&gt;
        &lt;a href=&quot;http://www.script-tutorials.com/powerful-chat-system/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
    &lt;/header&gt;
    &lt;div class=&quot;container&quot;&gt;
        {form}
    &lt;/div&gt;
    &lt;div class=&quot;container&quot;&gt;
        {chat}
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><p>It is easy layout, isn&#8217;t it?. Now, next template file for login form:</p><h4>templates/login_form.html</h4><pre class="brush:html">
&lt;div class=&quot;column&quot;&gt;
    &lt;h3&gt;Powerful Chat System Demonstration&lt;/h3&gt;
    &lt;p&gt;Our chat will contain next features: registration, main chat, profiles with avatars, ranking system, private messaging, custom rooms, moderation / administration and possible something else (in future).&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;column&quot;&gt;
    &lt;form class=&quot;login_form&quot; action=&quot;index.php&quot; method=&quot;post&quot;&gt;
        &lt;h3&gt;Log In&lt;/h3&gt;
        &lt;label&gt;Username:&lt;/label&gt;&lt;input type=&quot;text&quot; name=&quot;username&quot;&gt;
        &lt;label&gt;Password:&lt;/label&gt;&lt;input type=&quot;password&quot; name=&quot;password&quot;&gt;
        &lt;input type=&quot;submit&quot; name=&quot;LogIn&quot; value=&quot;Login&quot;&gt;
    &lt;/form&gt;
&lt;/div&gt;
</pre><p>Next one template &#8211; logout form:</p><h4>logout_form.html</h4><pre class="brush:html">
&lt;div class=&quot;column&quot;&gt;
    &lt;h3&gt;Hello {name}&lt;/h3&gt;
    &lt;h3&gt;Your status:&lt;/h3&gt;
    &lt;div&gt;{status}&lt;/div&gt;
    &lt;h3&gt;Your role:&lt;/h3&gt;
    &lt;div&gt;{role}&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;column&quot;&gt;
    &lt;a href=&quot;index.php?logout&quot;&gt;Log Out&lt;/a&gt;
&lt;/div&gt;
</pre><h3>Step 3. CSS</h3><p>This file contains styles of our page layout</p><h4>css/main.css</h4><pre class="brush:html">
/* page layout */
*{
    margin:0;
    padding:0;
}
body {
    background-color:#eee;
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
}
header {
    background-color:#212121;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    position:relative;
    width:100%;
    z-index:100;
}
header h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}
header a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}
header .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

/* main styles */
.container {
    background-color:#222;
    color: #bbb;
    margin: 20px auto;
    overflow: hidden;
    padding:20px;
    position: relative;
    width: 800px;
}
.column {
    float:left;
    width:48%;
}
.column:first-child {
    margin-right:4%;
}
.column &gt; * {
    color:#ddd;
    margin-bottom:10px;
}
.column h3 {
    color:#fff;
}
.login_form input,.login_form label {
    display:block;
    margin-bottom:5px;
}
input[type=text],
input[type=password] {
    width:200px;
}
input[type=submit]{
    height:30px;
    margin-top:10px;
    width:72px;
}
</pre><h3>Step 4. PHP</h3><p>Now, lets review php sources:</p><h4>index.php</h4><pre class="brush:php">
&lt;?php

// set error reporting level
if (version_compare(phpversion(), &quot;5.3.0&quot;, &quot;&gt;=&quot;) == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE);

require_once('classes/CMySQL.php'); // including service class to work with database
require_once('classes/CLogin.php'); // including service class to work with login processing

// login system init and generation code
$sLoginForm = $GLOBALS['CLogin']-&gt;getLoginBox();

$sChat = ($_SESSION['member_name'] &amp;&amp; $_SESSION['member_status'] == 'active') ? '&lt;h2&gt;TODO chat&lt;/h2&gt;' : '&lt;h2&gt;You have to login before use chat&lt;/h2&gt;';

echo strtr(file_get_contents('templates/main_page.html'), array('{form}' =&gt; $sLoginForm, '{chat}' =&gt; $sChat));
</pre><p>As we need only login processing for today &#8211; our index file is pretty small. New functional will appear in further articles. Here is sources of our login processor:</p><h4>classes/CLogin.php</h4><pre class="brush:php">
&lt;?php

class CLogin {

    // constructor
    function CLogin() {
        session_start();
    }

    // get login box function
    function getLoginBox() {
        if (isset($_GET['logout'])) { // logout processing
            if (isset($_SESSION['member_name']) &amp;&amp; isset($_SESSION['member_pass']))
                $this-&gt;performLogout();
        }

        if ($_POST &amp;&amp; $_POST['username'] &amp;&amp; $_POST['password']) { // login processing
            if ($this-&gt;checkLogin($_POST['username'], $_POST['password'], false)) { // successful login
                $this-&gt;performLogin($_POST['username'], $_POST['password']);
                header( &quot;Location:{$_SERVER['REQUEST_URI']}&quot; );
                exit;
            } else { // wrong login
                return file_get_contents('templates/login_form.html') . '&lt;h2&gt;Username or Password is incorrect&lt;/h2&gt;';
            }
        } else { // in case if we already logged (on refresh page):
            if (isset($_SESSION['member_name']) &amp;&amp; $_SESSION['member_name'] &amp;&amp; $_SESSION['member_pass']) {
                $aReplaces = array(
                    '{name}' =&gt; $_SESSION['member_name'],
                    '{status}' =&gt; $_SESSION['member_status'],
                    '{role}' =&gt; $_SESSION['member_role'],
                );
                return strtr(file_get_contents('templates/logout_form.html'), $aReplaces);
            }

            // otherwise - draw login form
            return file_get_contents('templates/login_form.html');
        }
    }

    // perform login
    function performLogin($sName, $sPass) {
        $this-&gt;performLogout();

        // make variables safe
        $sName = $GLOBALS['MySQL']-&gt;escape($sName);

        $aProfile = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `cs_profiles` WHERE `name`='{$sName}'&quot;);
        // $sPassEn = $aProfile['password'];
        $sSalt = $aProfile['salt'];
        $sStatus = $aProfile['status'];
        $sRole = $aProfile['role'];

        $sPass = sha1(md5($sPass) . $sSalt);

        $_SESSION['member_name'] = $sName;
        $_SESSION['member_pass'] = $sPass;
        $_SESSION['member_status'] = $sStatus;
        $_SESSION['member_role'] = $sRole;
    }

    // perform logout
    function performLogout() {
        unset($_SESSION['member_name']);
        unset($_SESSION['member_pass']);
        unset($_SESSION['member_status']);
        unset($_SESSION['member_role']);
    }

    // check login
    function checkLogin($sName, $sPass, $isHash = true) {
        // make variables safe
        $sName = $GLOBALS['MySQL']-&gt;escape($sName);
        $sPass = $GLOBALS['MySQL']-&gt;escape($sPass);

        $aProfile = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `cs_profiles` WHERE `name`='{$sName}'&quot;);
        $sPassEn = $aProfile['password'];

        if ($sName &amp;&amp; $sPass &amp;&amp; $sPassEn) {
            if (! $isHash) {
                $sSalt = $aProfile['salt'];
                $sPass = sha1(md5($sPass) . $sSalt);
            }
            return ($sPass == $sPassEn);
        }
        return false;
    }
}

$GLOBALS['CLogin'] = new CLogin();
</pre><p>I hope you still remember our <a
href="http://www.script-tutorials.com/creating-advance-level-login-system-with-logic-captcha/" target="_blank">previous article of advanced login system</a>. We will have similar system with using sha1 + md5 encryption. All profiles will kept in database.</p><h4>classes/CMySQL.php</h4><p>This is database service class. Available in package. Pay attention &#8211; database settings of our project is in this file.</p><hr
/><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - demo 218" href="http://www.script-tutorials.com/demos/218/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - package" href="http://www.script-tutorials.com/demos/218/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>I will hope that our new series of articles of chat system creation will be useful and interesting for you. If you want to share your ideas, or you noticed any weakness &#8211; don&#8217;t hesitate to contact us. Good luck and welcome back!</p><div
class="shr-publisher-1360"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/powerful-chat-system-lesson-3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/226/thumb.png" alt="Powerful Chat System &#8211; Lesson 3" /> <br
/> Powerful Chat System &#8211; Lesson 3</a></li><li> <a
href="http://www.script-tutorials.com/powerful-chat-system-lesson-2/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/221/thumb.png" alt="Powerful Chat System &#8211; Lesson 2" /> <br
/> Powerful Chat System &#8211; Lesson 2</a></li><li> <a
href="http://www.script-tutorials.com/how-to-easily-make-a-php-chat-application/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to Easily Make a PHP Chat Application" /> <br
/> How to Easily Make a PHP Chat Application</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/powerful-chat-system/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Pure HTML5 file upload</title><link>http://www.script-tutorials.com/pure-html5-file-upload/</link> <comments>http://www.script-tutorials.com/pure-html5-file-upload/#comments</comments> <pubDate>Fri, 09 Dec 2011 17:34:37 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[ajaxy]]></category> <category><![CDATA[html5]]></category> <category><![CDATA[photo upload]]></category> <category><![CDATA[preview]]></category> <category><![CDATA[upload]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1291</guid> <description><![CDATA[Pure HTML5 file upload Today we will be developing a great HTML5 file upload form with progress bar and preview (at client-side). We have already gave you jQuery based solution, but today&#8217;s application don&#8217;t require jQuery at all. All made in pure HTML5 Javascript. I&#8217;m going to use FileReader (html5) to implement live preview (without [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/ajax-file-upload-methods/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="Creating Ajax based file uploaders" /> Creating Ajax based file uploaders</a></li><li> <a
href="http://www.script-tutorials.com/html5-image-effects-app-adding-horizontal-flip/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/149/thumb.png" alt="Creating HTML5 Image Effects App &#8211; Adding Horizontal Flip" /> Creating HTML5 Image Effects App &#8211; Adding Horizontal Flip</a></li><li> <a
href="http://www.script-tutorials.com/html5-game-development-navigating-your-spaceship-lesson-3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/166/thumb.png" alt="HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3" /> HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Pure HTML5 file upload" alt="Pure HTML5 file upload" src="http://www.script-tutorials.com/demos/199/thumb.png"></div><p><strong>Pure HTML5 file upload</strong><br
/> <br
/>Today we will be developing a great HTML5 file upload form with progress bar and preview (at client-side). We have already gave you jQuery based solution, but today&#8217;s application don&#8217;t require jQuery at all. All made in pure HTML5 Javascript. I&#8217;m going to use FileReader (html5) to implement live preview (without uploading to server), and, going to use XMLHttpRequest to send data to server.<br
/> <span
id="more-1291"></span><br
/></p><p>Here are our demo and downloadable package:</p><h5 style="text-align: center;"><strong><a
title="Pure HTML5 file upload - demo 199" href="http://www.script-tutorials.com/demos/199/index.html" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Pure HTML5 file upload - package" href="http://www.script-tutorials.com/demos/199/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Ok, download the sources and lets begin !</p><hr
/><h3>Step 1. HTML</h3><p>At this page you can see out form for upload images</p><h4>index.html</h4><pre class="brush:html">
<!DOCTYPE html>
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;Pure HTML5 file upload | Script Tutorials&lt;/title&gt;
        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;script src=&quot;js/script.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;header&gt;
            &lt;h2&gt;Pure HTML5 file upload&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/pure-html5-file-upload/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/header&gt;
        &lt;div class=&quot;container&quot;&gt;
            &lt;div class=&quot;contr&quot;&gt;&lt;h2&gt;You can select the file (image) and click Upload button&lt;/h2&gt;&lt;/div&gt;

            &lt;div class=&quot;upload_form_cont&quot;&gt;
                &lt;form id=&quot;upload_form&quot; enctype=&quot;multipart/form-data&quot; method=&quot;post&quot; action=&quot;upload.php&quot;&gt;
                    &lt;div&gt;
                        &lt;div&gt;&lt;label for=&quot;image_file&quot;&gt;Please select image file&lt;/label&gt;&lt;/div&gt;
                        &lt;div&gt;&lt;input type=&quot;file&quot; name=&quot;image_file&quot; id=&quot;image_file&quot; onchange=&quot;fileSelected();&quot; /&gt;&lt;/div&gt;
                    &lt;/div&gt;
                    &lt;div&gt;
                        &lt;input type=&quot;button&quot; value=&quot;Upload&quot; onclick=&quot;startUploading()&quot; /&gt;
                    &lt;/div&gt;
                    &lt;div id=&quot;fileinfo&quot;&gt;
                        &lt;div id=&quot;filename&quot;&gt;&lt;/div&gt;
                        &lt;div id=&quot;filesize&quot;&gt;&lt;/div&gt;
                        &lt;div id=&quot;filetype&quot;&gt;&lt;/div&gt;
                        &lt;div id=&quot;filedim&quot;&gt;&lt;/div&gt;
                    &lt;/div&gt;
                    &lt;div id=&quot;error&quot;&gt;You should select valid image files only!&lt;/div&gt;
                    &lt;div id=&quot;error2&quot;&gt;An error occurred while uploading the file&lt;/div&gt;
                    &lt;div id=&quot;abort&quot;&gt;The upload has been canceled by the user or the browser dropped the connection&lt;/div&gt;
                    &lt;div id=&quot;warnsize&quot;&gt;Your file is very big. We can't accept it. Please select more small file&lt;/div&gt;

                    &lt;div id=&quot;progress_info&quot;&gt;
                        &lt;div id=&quot;progress&quot;&gt;&lt;/div&gt;
                        &lt;div id=&quot;progress_percent&quot;&gt;&amp;nbsp;&lt;/div&gt;
                        &lt;div class=&quot;clear_both&quot;&gt;&lt;/div&gt;
                        &lt;div&gt;
                            &lt;div id=&quot;speed&quot;&gt;&amp;nbsp;&lt;/div&gt;
                            &lt;div id=&quot;remaining&quot;&gt;&amp;nbsp;&lt;/div&gt;
                            &lt;div id=&quot;b_transfered&quot;&gt;&amp;nbsp;&lt;/div&gt;
                            &lt;div class=&quot;clear_both&quot;&gt;&lt;/div&gt;
                        &lt;/div&gt;
                        &lt;div id=&quot;upload_response&quot;&gt;&lt;/div&gt;
                    &lt;/div&gt;
                &lt;/form&gt;

                &lt;img id=&quot;preview&quot; /&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><h3>Step 2. CSS</h3><h4>css/main.css</h4><p>I have selected all necessary styles for our html5 upload form</p><h4>css/main.css</h4><pre class="brush:css">
.upload_form_cont {
    background: -moz-linear-gradient(#ffffff, #f2f2f2);
    background: -ms-linear-gradient(#ffffff, #f2f2f2);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ffffff), color-stop(100%, #f2f2f2));
    background: -webkit-linear-gradient(#ffffff, #f2f2f2);
    background: -o-linear-gradient(#ffffff, #f2f2f2);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f2f2f2');
    -ms-filter: &quot;progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f2f2f2')&quot;;
    background: linear-gradient(#ffffff, #f2f2f2);

    color:#000;
    overflow:hidden;
}
#upload_form {
    float:left;
    padding:20px;
    width:700px;
}
#preview {
    background-color:#fff;
    display:block;
    float:right;
    width:200px;
}
#upload_form &gt; div {
    margin-bottom:10px;
}
#speed,#remaining {
    float:left;
    width:100px;
}
#b_transfered {
    float:right;
    text-align:right;
}
.clear_both {
    clear:both;
}
input {
    border-radius:10px;
    -moz-border-radius:10px;
    -ms-border-radius:10px;
    -o-border-radius:10px;
    -webkit-border-radius:10px;

    border:1px solid #ccc;
    font-size:14pt;
    padding:5px 10px;
}
input[type=button] {
    background: -moz-linear-gradient(#ffffff, #dfdfdf);
    background: -ms-linear-gradient(#ffffff, #dfdfdf);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ffffff), color-stop(100%, #dfdfdf));
    background: -webkit-linear-gradient(#ffffff, #dfdfdf);
    background: -o-linear-gradient(#ffffff, #dfdfdf);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#dfdfdf');
    -ms-filter: &quot;progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#dfdfdf')&quot;;
    background: linear-gradient(#ffffff, #dfdfdf);
}
#image_file {
    width:400px;
}
#progress_info {
    font-size:10pt;
}
#fileinfo,#error,#error2,#abort,#warnsize {
    color:#aaa;
    display:none;
    font-size:10pt;
    font-style:italic;
    margin-top:10px;
}
#progress {
    border:1px solid #ccc;
    display:none;
    float:left;
    height:14px;

    border-radius:10px;
    -moz-border-radius:10px;
    -ms-border-radius:10px;
    -o-border-radius:10px;
    -webkit-border-radius:10px;

    background: -moz-linear-gradient(#66cc00, #4b9500);
    background: -ms-linear-gradient(#66cc00, #4b9500);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #66cc00), color-stop(100%, #4b9500));
    background: -webkit-linear-gradient(#66cc00, #4b9500);
    background: -o-linear-gradient(#66cc00, #4b9500);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#66cc00', endColorstr='#4b9500');
    -ms-filter: &quot;progid:DXImageTransform.Microsoft.gradient(startColorstr='#66cc00', endColorstr='#4b9500')&quot;;
    background: linear-gradient(#66cc00, #4b9500);
}
#progress_percent {
    float:right;
}
#upload_response {
    margin-top: 10px;
    padding: 20px;
    overflow: hidden;
    display: none;
    border: 1px solid #ccc;

    border-radius:10px;
    -moz-border-radius:10px;
    -ms-border-radius:10px;
    -o-border-radius:10px;
    -webkit-border-radius:10px;

    box-shadow: 0 0 5px #ccc;
    background: -moz-linear-gradient(#bbb, #eee);
    background: -ms-linear-gradient(#bbb, #eee);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #bbb), color-stop(100%, #eee));
    background: -webkit-linear-gradient(#bbb, #eee);
    background: -o-linear-gradient(#bbb, #eee);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#bbb', endColorstr='#eee');
    -ms-filter: &quot;progid:DXImageTransform.Microsoft.gradient(startColorstr='#bbb', endColorstr='#eee')&quot;;
    background: linear-gradient(#bbb, #eee);
}
</pre><h3>Step 3. HTML5 JS</h3><h4>js/script.js</h4><pre class="brush:js">
// common variables
var iBytesUploaded = 0;
var iBytesTotal = 0;
var iPreviousBytesLoaded = 0;
var iMaxFilesize = 1048576; // 1MB
var oTimer = 0;
var sResultFileSize = '';

function secondsToTime(secs) { // we will use this function to convert seconds in normal time format
    var hr = Math.floor(secs / 3600);
    var min = Math.floor((secs - (hr * 3600))/60);
    var sec = Math.floor(secs - (hr * 3600) -  (min * 60));

    if (hr &lt; 10) {hr = &quot;0&quot; + hr; }
    if (min &lt; 10) {min = &quot;0&quot; + min;}
    if (sec &lt; 10) {sec = &quot;0&quot; + sec;}
    if (hr) {hr = &quot;00&quot;;}
    return hr + ':' + min + ':' + sec;
};

function bytesToSize(bytes) {
    var sizes = ['Bytes', 'KB', 'MB'];
    if (bytes == 0) return 'n/a';
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};

function fileSelected() {

    // hide different warnings
    document.getElementById('upload_response').style.display = 'none';
    document.getElementById('error').style.display = 'none';
    document.getElementById('error2').style.display = 'none';
    document.getElementById('abort').style.display = 'none';
    document.getElementById('warnsize').style.display = 'none';

    // get selected file element
    var oFile = document.getElementById('image_file').files[0];

    // filter for image files
    var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
    if (! rFilter.test(oFile.type)) {
        document.getElementById('error').style.display = 'block';
        return;
    }

    // little test for filesize
    if (oFile.size &gt; iMaxFilesize) {
        document.getElementById('warnsize').style.display = 'block';
        return;
    }

    // get preview element
    var oImage = document.getElementById('preview');

    // prepare HTML5 FileReader
    var oReader = new FileReader();
        oReader.onload = function(e){

        // e.target.result contains the DataURL which we will use as a source of the image
        oImage.src = e.target.result;

        oImage.onload = function () { // binding onload event

            // we are going to display some custom image information here
            sResultFileSize = bytesToSize(oFile.size);
            document.getElementById('fileinfo').style.display = 'block';
            document.getElementById('filename').innerHTML = 'Name: ' + oFile.name;
            document.getElementById('filesize').innerHTML = 'Size: ' + sResultFileSize;
            document.getElementById('filetype').innerHTML = 'Type: ' + oFile.type;
            document.getElementById('filedim').innerHTML = 'Dimension: ' + oImage.naturalWidth + ' x ' + oImage.naturalHeight;
        };
    };

    // read selected file as DataURL
    oReader.readAsDataURL(oFile);
}

function startUploading() {
    // cleanup all temp states
    iPreviousBytesLoaded = 0;
    document.getElementById('upload_response').style.display = 'none';
    document.getElementById('error').style.display = 'none';
    document.getElementById('error2').style.display = 'none';
    document.getElementById('abort').style.display = 'none';
    document.getElementById('warnsize').style.display = 'none';
    document.getElementById('progress_percent').innerHTML = '';
    var oProgress = document.getElementById('progress');
    oProgress.style.display = 'block';
    oProgress.style.width = '0px';

    // get form data for POSTing
    //var vFD = document.getElementById('upload_form').getFormData(); // for FF3
    var vFD = new FormData(document.getElementById('upload_form')); 

    // create XMLHttpRequest object, adding few event listeners, and POSTing our data
    var oXHR = new XMLHttpRequest();
    oXHR.upload.addEventListener('progress', uploadProgress, false);
    oXHR.addEventListener('load', uploadFinish, false);
    oXHR.addEventListener('error', uploadError, false);
    oXHR.addEventListener('abort', uploadAbort, false);
    oXHR.open('POST', 'upload.php');
    oXHR.send(vFD);

    // set inner timer
    oTimer = setInterval(doInnerUpdates, 300);
}

function doInnerUpdates() { // we will use this function to display upload speed
    var iCB = iBytesUploaded;
    var iDiff = iCB - iPreviousBytesLoaded;

    // if nothing new loaded - exit
    if (iDiff == 0)
        return;

    iPreviousBytesLoaded = iCB;
    iDiff = iDiff * 2;
    var iBytesRem = iBytesTotal - iPreviousBytesLoaded;
    var secondsRemaining = iBytesRem / iDiff;

    // update speed info
    var iSpeed = iDiff.toString() + 'B/s';
    if (iDiff &gt; 1024 * 1024) {
        iSpeed = (Math.round(iDiff * 100/(1024*1024))/100).toString() + 'MB/s';
    } else if (iDiff &gt; 1024) {
        iSpeed =  (Math.round(iDiff * 100/1024)/100).toString() + 'KB/s';
    }

    document.getElementById('speed').innerHTML = iSpeed;
    document.getElementById('remaining').innerHTML = '| ' + secondsToTime(secondsRemaining);
}

function uploadProgress(e) { // upload process in progress
    if (e.lengthComputable) {
        iBytesUploaded = e.loaded;
        iBytesTotal = e.total;
        var iPercentComplete = Math.round(e.loaded * 100 / e.total);
        var iBytesTransfered = bytesToSize(iBytesUploaded);

        document.getElementById('progress_percent').innerHTML = iPercentComplete.toString() + '%';
        document.getElementById('progress').style.width = (iPercentComplete * 4).toString() + 'px';
        document.getElementById('b_transfered').innerHTML = iBytesTransfered;
        if (iPercentComplete == 100) {
            var oUploadResponse = document.getElementById('upload_response');
            oUploadResponse.innerHTML = '&lt;h1&gt;Please wait...processing&lt;/h1&gt;';
            oUploadResponse.style.display = 'block';
        }
    } else {
        document.getElementById('progress').innerHTML = 'unable to compute';
    }
}

function uploadFinish(e) { // upload successfully finished
    var oUploadResponse = document.getElementById('upload_response');
    oUploadResponse.innerHTML = e.target.responseText;
    oUploadResponse.style.display = 'block';

    document.getElementById('progress_percent').innerHTML = '100%';
    document.getElementById('progress').style.width = '400px';
    document.getElementById('filesize').innerHTML = sResultFileSize;
    document.getElementById('remaining').innerHTML = '| 00:00:00';

    clearInterval(oTimer);
}

function uploadError(e) { // upload error
    document.getElementById('error2').style.display = 'block';
    clearInterval(oTimer);
}  

function uploadAbort(e) { // upload abort
    document.getElementById('abort').style.display = 'block';
    clearInterval(oTimer);
}
</pre><p>Most of code is already commented. So I will hope that you will understand all this code. Anyway &#8211; how it working: when we select file &#8211; function &#8216;fileSelected&#8217; is executing. We filter all unnecessary formats (allow to upload next formats: bmp, gif, jpg, png, tif), in case of huge file &#8211; we will draw warning message. Then, through FileReader::readAsDataURL we will draw live preview of selected file. Plus, we will display another information about image: its name, size, type, and dimensions. Process of uploading is a little complicated. But generally, we have to prepare XMLHttpRequest object, add event listeners to next events: progress, load, error and abort. And after &#8211; post form data (I have used FormData class) to our &#8216;upload.php&#8217; receiver.</p><h3>Step 4. PHP</h3><h4>upload.php</h4><pre class="brush:js">
&lt;?php

function bytesToSize1024($bytes, $precision = 2) {
    $unit = array('B','KB','MB');
    return @round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), $precision).' '.$unit[$i];
}

$sFileName = $_FILES['image_file']['name'];
$sFileType = $_FILES['image_file']['type'];
$sFileSize = bytesToSize1024($_FILES['image_file']['size'], 1);

echo &lt;&lt;&lt;EOF
&lt;p&gt;Your file: {$sFileName} has been successfully received.&lt;/p&gt;
&lt;p&gt;Type: {$sFileType}&lt;/p&gt;
&lt;p&gt;Size: {$sFileSize}&lt;/p&gt;
EOF;
</pre><p>As you can see &#8211; I&#8217;m not uploading file. But, &#8216;echo&#8217; back all info about accepted file. This information will appear in our &lt;div id=&quot;upload_response&quot;&gt;&lt;/div&gt; element.</p><hr
/><h5 style="text-align: center;"><strong><a
title="Pure HTML5 file upload - demo 199" href="http://www.script-tutorials.com/demos/199/index.html" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Pure HTML5 file upload - package" href="http://www.script-tutorials.com/demos/199/source.zip" target="_blank" rel="nofollow">download in package</a></strong></h5><hr
/><h3>Conclusion</h3><p>Welcome back to read new awesome and unique articles about HTML5. Good luck!</p><div
class="shr-publisher-1291"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/ajax-file-upload-methods/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="Creating Ajax based file uploaders" /> <br
/> Creating Ajax based file uploaders</a></li><li> <a
href="http://www.script-tutorials.com/html5-image-effects-app-adding-horizontal-flip/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/149/thumb.png" alt="Creating HTML5 Image Effects App &#8211; Adding Horizontal Flip" /> <br
/> Creating HTML5 Image Effects App &#8211; Adding Horizontal Flip</a></li><li> <a
href="http://www.script-tutorials.com/html5-game-development-navigating-your-spaceship-lesson-3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/166/thumb.png" alt="HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3" /> <br
/> HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/pure-html5-file-upload/feed/</wfw:commentRss> <slash:comments>5</slash:comments> </item> <item><title>Creating Your Own Ajax Poll System</title><link>http://www.script-tutorials.com/creating-own-ajax-poll-system/</link> <comments>http://www.script-tutorials.com/creating-own-ajax-poll-system/#comments</comments> <pubDate>Wed, 16 Nov 2011 17:38:11 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[ajax tutorial]]></category> <category><![CDATA[poll]]></category> <category><![CDATA[polling system]]></category> <category><![CDATA[system]]></category> <category><![CDATA[tutorial]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1213</guid> <description><![CDATA[Creating own ajax poll system Today I prepared new interesting tutorial &#8211; we will creating own Poll system (AJAX) for your projects with PHP. Polls, answers and results I going to keep in single SQL table. When we will vote for one of variants &#8211; jQuery will POST data, and then we will animate our [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/how-to-create-own-commenting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/163/thumb.png" alt="Creating Your Own Commenting System from Scratch" /> Creating Your Own Commenting System from Scratch</a></li><li> <a
href="http://www.script-tutorials.com/how-to-create-own-voting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/155/thumb.png" alt="How to Create Your Own 5 Stars Voting System" /> How to Create Your Own 5 Stars Voting System</a></li><li> <a
href="http://www.script-tutorials.com/ajax-file-upload-methods/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="Creating Ajax based file uploaders" /> Creating Ajax based file uploaders</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Creating own ajax poll system" alt="Creating own ajax poll system" src="http://www.script-tutorials.com/demos/183/thumb.png"></div><p><strong>Creating own ajax poll system</strong><br
/> <br
/>Today I prepared new interesting tutorial &#8211; we will creating own Poll system (AJAX) for your projects with PHP. Polls, answers and results I going to keep in single SQL table. When we will vote for one of variants &#8211; jQuery will POST data, and then we will animate our results in realtime.<br
/> <span
id="more-1213"></span></p><h5 style="text-align: center;"><strong><a
title="Creating own ajax poll system - demo 183" href="http://www.script-tutorials.com/demos/183/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Creating own ajax poll system - package" href="http://www.script-tutorials.com/demos/183/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. SQL</h3><p>We will need to add one table into our database:</p><pre class="brush:php">
CREATE TABLE `s183_polls` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `title` varchar(255) default '',
  `answers` text NOT NULL,
  `results` varchar(60) NOT NULL default '',
  `total_votes` int(10) NOT NULL default '0',
  `when` int(10) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

INSERT INTO `s183_polls` (`id`, `title`, `answers`, `results`, `total_votes`, `when`) VALUES
(NULL, 'First poll question', 'Answer 1&lt;sep&gt;Answer 2&lt;sep&gt;Answer 3&lt;sep&gt;Answer 4', '', 0, UNIX_TIMESTAMP()),
(NULL, 'Second poll question', 'Answer 21&lt;sep&gt;Answer 22&lt;sep&gt;Answer 23&lt;sep&gt;Answer 24', '', 0, UNIX_TIMESTAMP()+1),
(NULL, 'Third poll question', 'Answer 31&lt;sep&gt;Answer 32&lt;sep&gt;Answer 33&lt;sep&gt;Answer 34', '', 0, UNIX_TIMESTAMP()+2),
(NULL, 'Forth poll question', 'Answer 41&lt;sep&gt;Answer 42&lt;sep&gt;Answer 43&lt;sep&gt;Answer 44', '', 0, UNIX_TIMESTAMP()+3),
(NULL, 'Fifth poll question', 'Answer 51&lt;sep&gt;Answer 52&lt;sep&gt;Answer 53&lt;sep&gt;Answer 54', '', 0, UNIX_TIMESTAMP()+4);
</pre><p>This is pur main Polls table.</p><h3>Step 2. PHP</h3><p>Here are source code of our main file:</p><h4>index.php</h4><pre class="brush:php">
&lt;?php
// disable  warnings
if (version_compare(phpversion(), &quot;5.3.0&quot;, &quot;&gt;=&quot;)  == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE); 

require_once('classes/CMySQL.php'); // including service class to work with database

if ($_POST['do'] == 'vote') { // in case if we submitted poll
    $iPollId = (int)$_POST['id'];
    $iAnswer = (int)$_POST['answer'];

    if ($iPollId &amp;&amp; $iAnswer &gt;= 0 &amp;&amp; ! isset($_COOKIE['av' . $iPollId])) {
        // get poll info
        $aPollInfo = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `s183_polls` WHERE `id` = '{$iPollId}'&quot;);

        // updating of poll results
        $aAnswers = explode('&lt;sep&gt;', $aPollInfo['answers']);
        $iCnt = count($aAnswers);
        $aVotes = ($aPollInfo['results'] == '') ? array_fill(0, $iCnt, 0) : explode('&lt;sep&gt;', $aPollInfo['results']);
        $aVotes[$iAnswer]++;
        $iVotesCount = array_sum($aVotes);
        $sVotes = implode('&lt;sep&gt;', $aVotes);
        $GLOBALS['MySQL']-&gt;res(&quot;UPDATE `s183_polls` SET `results` = '{$sVotes}', `total_votes` = {$iVotesCount} WHERE `id` = {$iPollId}&quot;);

        // recalculation of percents
        $iVotesCnt = $aPollInfo['total_votes'] + 1;
        $aPercents = array();
        foreach ($aAnswers as $i =&gt; $sAnswer) {
            $aPercents[$i] = round( (0 != $iVotesCnt ? (( $aVotes[$i] / $iVotesCnt ) * 100) : 0), 1);
        }

        setcookie('av' . $iPollId, '1', time() + 24*3600, '/'); // easy protection from duplicate votes

        // return back to JS
        echo json_encode($aPercents);
        exit;
    } else {
        exit;
    }
}

$sCode = '';
$iItemId = (int)$_GET['id'];
if ($iItemId) { // View item output
    $aItemInfo = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `s183_polls` WHERE `id` = '{$iItemId}'&quot;); // get poll info

    $aAnswers = explode('&lt;sep&gt;', $aItemInfo['answers']);
    $iCnt = count($aAnswers);
    $aVotes = ($aItemInfo['results'] == '') ? array_fill(0, $iCnt, 0) : explode('&lt;sep&gt;', $aItemInfo['results']);

    $iVotesCnt = $aItemInfo['total_votes'];

    $sAnswers = '';
    foreach ($aAnswers as $i =&gt; $sAnswer) {
        $fPercent = round((0 != $iVotesCnt ? (($aVotes[$i] / $iVotesCnt) * 100) : 0), 1);
        $sAnswers .= &quot;&lt;div id='{$i}'&gt;&lt;div&gt;{$sAnswer} (&lt;span&gt;{$aVotes[$i]}&lt;/span&gt;)&lt;/div&gt;&lt;div class='row' style='width:{$fPercent}%'&gt;{$fPercent}%&lt;/div&gt;&lt;/div&gt;&quot;;
    }

    ob_start();
    ?&gt;
&lt;h1&gt;&lt;?= $aItemInfo['title'] ?&gt;&lt;/h1&gt;
&lt;h3&gt;&lt;?= date('F j, Y', $aItemInfo['when']) ?&gt;&lt;/h3&gt;&lt;hr /&gt;
&lt;div class=&quot;answers&quot;&gt;&lt;?= $sAnswers ?&gt;&lt;/div&gt;
&lt;hr /&gt;&lt;h3&gt;&lt;a href=&quot;&lt;?= $_SERVER['PHP_SELF'] ?&gt;&quot;&gt;back&lt;/a&gt;&lt;/h3&gt;
&lt;script&gt;
$(function(){
    $('.answers &gt; div').click(function () {

        var answer = $(this).attr('id');
        var $span = $(this).find('span');

        $.post('&lt;?= $_SERVER['PHP_SELF'] ?&gt;', {id: &lt;?= $iItemId ?&gt;, answer: answer, do: 'vote'},
            function(data){
                if (data) {
                    var da = eval('(' + data + ')');
                    for (var p in da) {
                        $($('.answers &gt; div .row')[p]).animate({
                            width: da[p] + &quot;%&quot;
                        }, 500);
                        $($('.answers &gt; div .row')[p]).text(da[p] + &quot;%&quot;);
                    }
                    $span.text(parseInt($span.text()) + 1);
                }
            }
        );
    });
});
&lt;/script&gt;
    &lt;?
    $sCode .= ob_get_clean();
} else {
    $sCode .= '&lt;h1&gt;List of polls:&lt;/h1&gt;';

    // taking info about all polls from database
    $aItems = $GLOBALS['MySQL']-&gt;getAll(&quot;SELECT * FROM `s183_polls` ORDER by `when` ASC&quot;);
    foreach ($aItems as $i =&gt; $aItemInfo) {
        $sCode .= '&lt;h2&gt;&lt;a href=&quot;'.$_SERVER['PHP_SELF'].'?id='.$aItemInfo['id'].'&quot;&gt;'.$aItemInfo['title'].'&lt;/a&gt;&lt;/h2&gt;';
    }
}

?&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;Creating own ajax poll system | Script Tutorials&lt;/title&gt;

        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-1.5.2.min.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div class=&quot;container&quot;&gt;
            &lt;?= $sCode ?&gt;
        &lt;/div&gt;
        &lt;footer&gt;
            &lt;h2&gt;Creating own own ajax poll system&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/creating-own-ajax-poll-system/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/footer&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><p>When we open this page in first time &#8211; it will draw list of polls. Each poll unit have own page. At this page we going to display Poll title, date of adding and all possible answers. On click &#8211; script will send (POST) data to same script. In this moment we are adding this vote, and then we will send back new percentages for all variants. And jQuery will re-animate all these bars. I added my comments in most of places for better understanding.</p><p>I have another one PHP file in my project:</p><h4>classes/CMySQL.php</h4><p>This is service class to work with database prepared by me. This is nice class which you can use too. Database connection details present in that class file in few variables, sure that you will able to configure this to your database. I will not publish sources of this file &#8211; this is not necessary right now. Available in package.</p><h3>Step 3. JS</h3><h4>js/jquery-1.5.2.min.js</h4><p>This is just jQuery library. Available in package.</p><h3>Step 4. CSS</h3><p>Now &#8211; all used CSS styles:</p><h4>css/main.css</h4><pre class="brush:js">
*{
    margin:0;
    padding:0;
}
body {
    background-repeat:no-repeat;
    background-color:#bababa;
    background-image: -webkit-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: -moz-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: -o-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
    min-height:600px;
}
footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}
footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}
footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}
footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}
.container {
    border:3px #111 solid;
    color:#000;
    margin:20px auto;
    padding:15px;
    position:relative;
    text-align:center;
    width:500px;

    border-radius:15px;
    -moz-border-radius:15px;
    -webkit-border-radius:15px;
}

.answers &gt; div {
    cursor:pointer;
    margin:0 0 0 40px;
    padding:10px;
    text-align:left;
}
.answers &gt; div:hover {
    background-color: rgba(255, 255, 255, 0.4);
}
.answers div .row {
     background-color:#0f0;
}
</pre><hr
/><h5 style="text-align: center;"><strong><a
title="Creating own ajax poll system - demo 183" href="http://www.script-tutorials.com/demos/183/index.php" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Creating own ajax poll system - package" href="http://www.script-tutorials.com/demos/183/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>Today we prepared great AJAX Poll system for your website. Sure that this material will useful for your own projects. Good luck in your work!</p><div
class="shr-publisher-1213"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/how-to-create-own-commenting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/163/thumb.png" alt="Creating Your Own Commenting System from Scratch" /> <br
/> Creating Your Own Commenting System from Scratch</a></li><li> <a
href="http://www.script-tutorials.com/how-to-create-own-voting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/155/thumb.png" alt="How to Create Your Own 5 Stars Voting System" /> <br
/> How to Create Your Own 5 Stars Voting System</a></li><li> <a
href="http://www.script-tutorials.com/ajax-file-upload-methods/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="Creating Ajax based file uploaders" /> <br
/> Creating Ajax based file uploaders</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/creating-own-ajax-poll-system/feed/</wfw:commentRss> <slash:comments>5</slash:comments> </item> <item><title>Creating a Diary style PHP Guestbook</title><link>http://www.script-tutorials.com/php-guestbook/</link> <comments>http://www.script-tutorials.com/php-guestbook/#comments</comments> <pubDate>Mon, 07 Nov 2011 18:02:58 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[diary]]></category> <category><![CDATA[guestbook]]></category> <category><![CDATA[script]]></category> <category><![CDATA[style]]></category> <category><![CDATA[tutorial]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1187</guid> <description><![CDATA[PHP guestbook Today I prepared new interesting tutorial &#8211; I will tell how you can create ajax PHP guestbook with own unique design. Our records will be saved into SQL database. This table will contain next info: name of sender, email, guestbook record, date-time of record and ip of sender. Of course, we will use [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/how-to-make-a-php-guestbook-with-math-captcha-security/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to make a PHP Guestbook with Math Captcha Security" /> How to make a PHP Guestbook with Math Captcha Security</a></li><li> <a
href="http://www.script-tutorials.com/how-to-create-own-commenting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/163/thumb.png" alt="Creating Your Own Commenting System from Scratch" /> Creating Your Own Commenting System from Scratch</a></li><li> <a
href="http://www.script-tutorials.com/autocomplete-with-php-jquery-mysql-and-xml/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/160/thumb.png" alt="Autocomplete with PHP, jQuery, MySQL and XML" /> Autocomplete with PHP, jQuery, MySQL and XML</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="PHP guestbook" alt="PHP guestbook" src="http://www.script-tutorials.com/demos/178/thumb.png"></div><p><strong>PHP guestbook</strong><br
/> <br
/>Today I prepared new interesting tutorial &#8211; I will tell how you can create ajax PHP guestbook with own unique design. Our records will be saved into SQL database. This table will contain next info: name of sender, email, guestbook record, date-time of record and ip of sender. Of course, we will use jQuery too (to make it ajaxy). One of important features will spam protection (we can post no more than one record every 10 minutes)!<br
/> <span
id="more-1187"></span></p><h5 style="text-align: center;"><strong><a
title="PHP guestbook - demo 178" href="http://www.script-tutorials.com/demos/178/guestbook.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="PHP guestbook - package" href="http://www.script-tutorials.com/demos/178/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. SQL</h3><p>We need to add one table to our database (to store our records):</p><pre class="brush:php">
CREATE TABLE IF NOT EXISTS `s178_guestbook` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `name` varchar(255) default '',
  `email` varchar(255) default '',
  `description` varchar(255) default '',
  `when` int(11) NOT NULL default '0',
  `ip` varchar(20) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</pre><h3>Step 2. PHP</h3><p>Here are source code of our main file:</p><h4>guestbook.php</h4><pre class="brush:php">
&lt;?php
// disabling possible warnings
if (version_compare(phpversion(), &quot;5.3.0&quot;, &quot;&gt;=&quot;)  == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE); 

require_once('classes/CMySQL.php'); // including service class to work with database

// get visitor IP
function getVisitorIP() {
    $ip = &quot;0.0.0.0&quot;;
    if( ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) &amp;&amp; ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif( ( isset( $_SERVER['HTTP_CLIENT_IP'])) &amp;&amp; (!empty($_SERVER['HTTP_CLIENT_IP'] ) ) ) {
        $ip = explode(&quot;.&quot;,$_SERVER['HTTP_CLIENT_IP']);
        $ip = $ip[3].&quot;.&quot;.$ip[2].&quot;.&quot;.$ip[1].&quot;.&quot;.$ip[0];
    } elseif((!isset( $_SERVER['HTTP_X_FORWARDED_FOR'])) || (empty($_SERVER['HTTP_X_FORWARDED_FOR']))) {
        if ((!isset( $_SERVER['HTTP_CLIENT_IP'])) &amp;&amp; (empty($_SERVER['HTTP_CLIENT_IP']))) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    }
    return $ip;
}

// get last guestbook records
function getLastRecords($iLimit = 3) {
    $sRecords = '';
    $aRecords = $GLOBALS['MySQL']-&gt;getAll(&quot;SELECT * FROM `s178_guestbook` ORDER BY `id` DESC LIMIT {$iLimit}&quot;);
    foreach ($aRecords as $i =&gt; $aInfo) {
        $sWhen = date('F j, Y H:i', $aInfo['when']);
        $sRecords .= &lt;&lt;&lt;EOF
&lt;div class=&quot;record&quot; id=&quot;{$aInfo['id']}&quot;&gt;
    &lt;p&gt;Record from {$aInfo['name']} &lt;span&gt;({$sWhen})&lt;/span&gt;:&lt;/p&gt;
    &lt;p&gt;{$aInfo['description']}&lt;/p&gt;
&lt;/div&gt;
EOF;
    }
    return $sRecords;
}

if ($_POST) { // accepting new records

    $sIp = getVisitorIP();
    $sName = $GLOBALS['MySQL']-&gt;escape(strip_tags($_POST['name']));
    $sEmail = $GLOBALS['MySQL']-&gt;escape(strip_tags($_POST['name']));
    $sDesc = $GLOBALS['MySQL']-&gt;escape(strip_tags($_POST['text']));

    if ($sName &amp;&amp; $sEmail &amp;&amp; $sDesc &amp;&amp; $sIp) {

        // spam protection
        $iOldId = $GLOBALS['MySQL']-&gt;getOne(&quot;SELECT `id` FROM `s178_guestbook` WHERE `ip` = '{$sIp}' AND `when` &gt;= UNIX_TIMESTAMP() - 600 LIMIT 1&quot;);
        if (! $iOldId) {

            // allow to add comment
            $GLOBALS['MySQL']-&gt;res(&quot;INSERT INTO `s178_guestbook` SET `name` = '{$sName}', `email` = '{$sEmail}', `description` = '{$sDesc}', `when` = UNIX_TIMESTAMP(), `ip` = '{$sIp}'&quot;);

            // drawing last 10 records
            $sOut = getLastRecords();
            echo $sOut;
            exit;
        }
    }
    echo 1;
    exit;
}

// drawing last 10 records
$sRecords = getLastRecords();

ob_start();
?&gt;
&lt;div class=&quot;container&quot; id=&quot;records&quot;&gt;
    &lt;div id=&quot;col1&quot;&gt;
        &lt;h2&gt;Guestbook Records&lt;/h2&gt;
        &lt;div id=&quot;records_list&quot;&gt;&lt;?= $sRecords ?&gt;&lt;/div&gt;
    &lt;/div&gt;

    &lt;div id=&quot;col2&quot;&gt;
        &lt;h2&gt;Add your record here&lt;/h2&gt;
        &lt;script type=&quot;text/javascript&quot;&gt;
        function submitComment(e) {
            var name = $('#name').val();
            var email = $('#email').val();
            var text = $('#text').val();

            if (name &amp;&amp; email &amp;&amp; text) {
                $.post('guestbook.php', { 'name': name, 'email': email, 'text': text },
                    function(data){
                        if (data != '1') {
                          $('#records_list').fadeOut(1000, function () {
                            $(this).html(data);
                            $(this).fadeIn(1000);
                          });
                        } else {
                          $('#warning2').fadeIn(2000, function () {
                            $(this).fadeOut(2000);
                          });
                        }
                    }
                );
            } else {
              $('#warning1').fadeIn(2000, function () {
                $(this).fadeOut(2000);
              });
            }
        };
        &lt;/script&gt;

        &lt;form onsubmit=&quot;submitComment(this); return false;&quot;&gt;
            &lt;table&gt;
                &lt;tr&gt;&lt;td class=&quot;label&quot;&gt;&lt;label&gt;Your name: &lt;/label&gt;&lt;/td&gt;&lt;td class=&quot;field&quot;&gt;&lt;input type=&quot;text&quot; value=&quot;&quot; title=&quot;Please enter your name&quot; id=&quot;name&quot; /&gt;&lt;/td&gt;&lt;/tr&gt;
                &lt;tr&gt;&lt;td class=&quot;label&quot;&gt;&lt;label&gt;Your email: &lt;/label&gt;&lt;/td&gt;&lt;td class=&quot;field&quot;&gt;&lt;input type=&quot;text&quot; value=&quot;&quot; title=&quot;Please enter your email&quot; id=&quot;email&quot; /&gt;&lt;/td&gt;&lt;/tr&gt;
                &lt;tr&gt;&lt;td class=&quot;label&quot;&gt;&lt;label&gt;Comment: &lt;/label&gt;&lt;/td&gt;&lt;td class=&quot;field&quot;&gt;&lt;textarea name=&quot;text&quot; id=&quot;text&quot; maxlength=&quot;255&quot;&gt;&lt;/textarea&gt;&lt;/td&gt;&lt;/tr&gt;
                &lt;tr&gt;&lt;td class=&quot;label&quot;&gt;&amp;nbsp;&lt;/td&gt;&lt;td class=&quot;field&quot;&gt;
                    &lt;div id=&quot;warning1&quot; style=&quot;display:none&quot;&gt;Don`t forget to fill all required fields&lt;/div&gt;
                    &lt;div id=&quot;warning2&quot; style=&quot;display:none&quot;&gt;You can post no more than one comment every 10 minutes (spam protection)&lt;/div&gt;
                    &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;
                &lt;/td&gt;&lt;/tr&gt;
            &lt;/table&gt;
        &lt;/form&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;?
$sGuestbookBlock = ob_get_clean();

?&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;PHP guestbook | Script Tutorials&lt;/title&gt;

        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;!--[if lt IE 9]&gt;
          &lt;script src=&quot;http://html5shiv.googlecode.com/svn/trunk/html5.js&quot;&gt;&lt;/script&gt;
        &lt;![endif]--&gt;
        &lt;script src=&quot;http://code.jquery.com/jquery-latest.min.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;?= $sGuestbookBlock ?&gt;
        &lt;footer&gt;
            &lt;h2&gt;PHP guestbook&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/php-guestbook/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/footer&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><p>When we open this page we will see book, at left side we will draw list of last three records, at right &#8211; form of posting new records. When we submitting form &#8211; script sending POST data (to same php page), script saving this data to database, and returning us list of fresh 3 records. Then, via fading effect we draw returned data at left column. All code contains comments &#8211; read it for better understanding code. Ok, next PHP file is:</p><h4>classes/CMySQL.php</h4><p>This is my own service class to work with database. This is nice class which you can use too. Database connection details located in this class in few variables, sure that you will able to configure this to your database. I don`t will publish its sources &#8211; this is not necessary for now. Available in package.</p><h3>Step 3. CSS</h3><p>Now &#8211; all used CSS styles:</p><h4>css/main.css</h4><pre class="brush:js">
*{
    margin:0;
    padding:0;
}
body {
    background-color:#fff;
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
}
footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}
footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}
footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}
footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

.container {
    background: transparent url(../images/book_open.jpg) no-repeat top center ;
    color: #000000;
    height: 600px;
    margin: 20px auto;
    overflow: hidden;
    padding: 35px 100px;
    position: relative;
    width: 600px;
}
#col1, #col2 {
    float: left;
    margin: 0 10px;
    overflow: hidden;
    text-align: center;
    width: 280px;
}
#col1 {
    -webkit-transform: rotate(3deg);
    -moz-transform: rotate(3deg);
    -ms-transform: rotate(3deg);
    -o-transform: rotate(3deg);
}
#records form {
    margin:10px 0;
    padding:10px;
    text-align:left;
}
#records table td.label {
    color: #000;
    font-size: 13px;
    padding-right: 3px;
    text-align: right;
}
#records table label {
    font-size: 12px;
    vertical-align: middle;
}
#records table td.field input, #records table td.field textarea {
    background-color: rgba(255, 255, 255, 0.4);
    border: 0px solid #96A6C5;
    font-family: Verdana,Arial,sans-serif;
    font-size: 13px;
    margin-top: 2px;
    padding: 6px;
    width: 190px;
}
#records table td.field input[type=submit] {
    background-color: rgba(200, 200, 200, 0.4);
    cursor: pointer;
    float:right;
    width: 100px;
}
#records table td.field input[type=submit]:hover {
    background-color: rgba(200, 200, 200, 0.8);
}
#records_list {
    text-align:left;
}
#records_list .record {
    border-top: 1px solid #000000;
    font-size: 13px;
    padding: 10px;
}
#records_list .record:first-child {
    border-top-width:0px;
}
#records_list .record p:first-child {
    font-weight:bold;
    font-size:11px;
}
</pre><hr
/><h5 style="text-align: center;"><strong><a
title="PHP guestbook - demo 178" href="http://www.script-tutorials.com/demos/178/guestbook.php" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="PHP guestbook - package" href="http://www.script-tutorials.com/demos/178/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>Today we have prepared great PHP guestbook for your website. Sure that this material will be useful for your own projects. Good luck in your work!</p><div
class="shr-publisher-1187"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/how-to-make-a-php-guestbook-with-math-captcha-security/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to make a PHP Guestbook with Math Captcha Security" /> <br
/> How to make a PHP Guestbook with Math Captcha Security</a></li><li> <a
href="http://www.script-tutorials.com/how-to-create-own-commenting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/163/thumb.png" alt="Creating Your Own Commenting System from Scratch" /> <br
/> Creating Your Own Commenting System from Scratch</a></li><li> <a
href="http://www.script-tutorials.com/autocomplete-with-php-jquery-mysql-and-xml/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/160/thumb.png" alt="Autocomplete with PHP, jQuery, MySQL and XML" /> <br
/> Autocomplete with PHP, jQuery, MySQL and XML</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/php-guestbook/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Creating Your Own Commenting System from Scratch</title><link>http://www.script-tutorials.com/how-to-create-own-commenting-system/</link> <comments>http://www.script-tutorials.com/how-to-create-own-commenting-system/#comments</comments> <pubDate>Fri, 14 Oct 2011 17:08:46 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[commenting system]]></category> <category><![CDATA[comments]]></category> <category><![CDATA[creating]]></category> <category><![CDATA[script]]></category> <category><![CDATA[system]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1109</guid> <description><![CDATA[How to create own commenting system Today I prepared new interesting article &#8211; I will tell how you can create own commenting system (AJAX) for your items (any units at your website) with PHP. For our demonstration &#8211; I prepared two SQL tables: first table will keep records of our items. It contain several fields: [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/how-to-create-own-voting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/155/thumb.png" alt="How to Create Your Own 5 Stars Voting System" /> How to Create Your Own 5 Stars Voting System</a></li><li> <a
href="http://www.script-tutorials.com/php-guestbook/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/178/thumb.png" alt="Creating a Diary style PHP Guestbook" /> Creating a Diary style PHP Guestbook</a></li><li> <a
href="http://www.script-tutorials.com/creating-own-ajax-poll-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/183/thumb.png" alt="Creating Your Own Ajax Poll System" /> Creating Your Own Ajax Poll System</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="How to create own commenting system" alt="How to create own commenting system" src="http://www.script-tutorials.com/demos/163/thumb.png"></div><p><strong>How to create own commenting system</strong><br
/> <br
/>Today I prepared new interesting article &#8211; I will tell how you can create own commenting system (AJAX) for your items (any units at your website) with PHP. For our demonstration &#8211; I prepared two SQL tables: first table will keep records of our items. It contain several fields: title, description, time of adding and comments count. Another table will keep records of comments. We will use jQuery too (for better interface behavior). One of features will spam protection (we can post no more than one comment every 10 minutes)!<br
/> <span
id="more-1109"></span></p><h5 style="text-align: center;"><strong><a
title="How to create own commenting system - demo 163" href="http://www.script-tutorials.com/demos/163/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="How to create own commenting system - package" href="http://www.script-tutorials.com/demos/163/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. SQL</h3><p>We will need to add 2 tables into our database:</p><pre class="brush:php">
CREATE TABLE IF NOT EXISTS `s163_items` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `title` varchar(255) default '',
  `description` text NOT NULL,
  `when` int(11) NOT NULL default '0',
  `comments_count` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `s163_items` (`title`, `description`, `when`, `comments_count`) VALUES
('Item #1', 'Here are you can put description of Item #1', UNIX_TIMESTAMP(), '0'),
('Item #2', 'Here are you can put description of Item #2', UNIX_TIMESTAMP()+1, '0'),
('Item #3', 'Here are you can put description of Item #3', UNIX_TIMESTAMP()+2, '0'),
('Item #4', 'Here are you can put description of Item #4', UNIX_TIMESTAMP()+3, '0'),
('Item #5', 'Here are you can put description of Item #5', UNIX_TIMESTAMP()+4, '0');

CREATE TABLE IF NOT EXISTS `s163_items_cmts` (
  `c_id` int(11) NOT NULL AUTO_INCREMENT ,
  `c_item_id` int(12) NOT NULL default '0',
  `c_ip` varchar(20) default NULL,
  `c_name` varchar(64) default '',
  `c_text` text NOT NULL ,
  `c_when` int(11) NOT NULL default '0',
  PRIMARY KEY (`c_id`),
  KEY `c_item_id` (`c_item_id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8;
</pre><p>This is simple tables: first for records of items, second one &#8211; for comments</p><h3>Step 2. PHP</h3><p>Here are source code of our main file:</p><h4>index.php</h4><pre class="brush:php">
&lt;?php
// disabling possible warnings
if (version_compare(phpversion(), &quot;5.3.0&quot;, &quot;&gt;=&quot;)  == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE); 

require_once('classes/CMySQL.php'); // including service class to work with database

$sCode = '';
$iItemId = (int)$_GET['id'];
if ($iItemId) { // View item output
    $aItemInfo = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `s163_items` WHERE `id` = '{$iItemId}'&quot;); // getting info about item from database
    $sCode .= '&lt;h1&gt;'.$aItemInfo['title'].'&lt;/h1&gt;';
    $sCode .= '&lt;h3&gt;'.date('F j, Y', $aItemInfo['when']).'&lt;/h3&gt;';
    $sCode .= '&lt;h2&gt;Description:&lt;/h2&gt;';
    $sCode .= '&lt;h3&gt;'.$aItemInfo['description'].'&lt;/h3&gt;';
    $sCode .= '&lt;h3&gt;&lt;a href=&quot;'.$_SERVER['PHP_SELF'].'&quot;&gt;back&lt;/a&gt;&lt;/h3&gt;';

    // drawing last 5 comments
    $sComments = '';
    $aComments = $GLOBALS['MySQL']-&gt;getAll(&quot;SELECT * FROM `s163_items_cmts` WHERE `c_item_id` = '{$iItemId}' ORDER BY `c_when` DESC LIMIT 5&quot;);
    foreach ($aComments as $i =&gt; $aCmtsInfo) {
        $sWhen = date('F j, Y H:i', $aCmtsInfo['c_when']);
        $sComments .= &lt;&lt;&lt;EOF
&lt;div class=&quot;comment&quot; id=&quot;{$aCmtsInfo['c_id']}&quot;&gt;
    &lt;p&gt;Comment from {$aCmtsInfo['c_name']} &lt;span&gt;({$sWhen})&lt;/span&gt;:&lt;/p&gt;
    &lt;p&gt;{$aCmtsInfo['c_text']}&lt;/p&gt;
&lt;/div&gt;
EOF;
    }

    ob_start();
    ?&gt;
    &lt;div class=&quot;container&quot; id=&quot;comments&quot;&gt;
        &lt;h2&gt;Comments&lt;/h2&gt;
        &lt;script type=&quot;text/javascript&quot;&gt;
        function submitComment(e) {
            var sName = $('#name').val();
            var sText = $('#text').val();

            if (sName &amp;&amp; sText) {
                $.post('comment.php', { name: sName, text: sText, id: &lt;?= $iItemId ?&gt; },
                    function(data){
                        if (data != '1') {
                          $('#comments_list').fadeOut(1000, function () {
                            $(this).html(data);
                            $(this).fadeIn(1000);
                          });
                        } else {
                          $('#comments_warning2').fadeIn(1000, function () {
                            $(this).fadeOut(1000);
                          });
                        }
                    }
                );
            } else {
              $('#comments_warning1').fadeIn(1000, function () {
                $(this).fadeOut(1000);
              });
            }
        };
        &lt;/script&gt;

        &lt;div id=&quot;comments_warning1&quot; style=&quot;display:none&quot;&gt;Don`t forget to fill both fields (Name and Comment)&lt;/div&gt;
        &lt;div id=&quot;comments_warning2&quot; style=&quot;display:none&quot;&gt;You can post no more than one comment every 10 minutes (spam protection)&lt;/div&gt;
        &lt;form onsubmit=&quot;submitComment(this); return false;&quot;&gt;
            &lt;table&gt;
                &lt;tr&gt;&lt;td class=&quot;label&quot;&gt;&lt;label&gt;Your name: &lt;/label&gt;&lt;/td&gt;&lt;td class=&quot;field&quot;&gt;&lt;input type=&quot;text&quot; value=&quot;&quot; title=&quot;Please enter your name&quot; id=&quot;name&quot; /&gt;&lt;/td&gt;&lt;/tr&gt;
                &lt;tr&gt;&lt;td class=&quot;label&quot;&gt;&lt;label&gt;Comment: &lt;/label&gt;&lt;/td&gt;&lt;td class=&quot;field&quot;&gt;&lt;textarea name=&quot;text&quot; id=&quot;text&quot;&gt;&lt;/textarea&gt;&lt;/td&gt;&lt;/tr&gt;
                &lt;tr&gt;&lt;td class=&quot;label&quot;&gt;&amp;nbsp;&lt;/td&gt;&lt;td class=&quot;field&quot;&gt;&lt;input type=&quot;submit&quot; value=&quot;Post comment&quot; /&gt;&lt;/td&gt;&lt;/tr&gt;
            &lt;/table&gt;
        &lt;/form&gt;
        &lt;div id=&quot;comments_list&quot;&gt;&lt;?= $sComments ?&gt;&lt;/div&gt;
    &lt;/div&gt;
    &lt;?
    $sCommentsBlock = ob_get_clean();

} else {
    $sCode .= '&lt;h1&gt;List of items:&lt;/h1&gt;';

    $aItems = $GLOBALS['MySQL']-&gt;getAll(&quot;SELECT * FROM `s163_items` ORDER by `when` ASC&quot;); // taking info about all items from database
    foreach ($aItems as $i =&gt; $aItemInfo) {
        $sCode .= '&lt;h2&gt;&lt;a href=&quot;'.$_SERVER['PHP_SELF'].'?id='.$aItemInfo['id'].'&quot;&gt;'.$aItemInfo['title'].' item&lt;/a&gt;&lt;/h2&gt;';
    }
}

?&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;Creating own commenting system | Script Tutorials&lt;/title&gt;

        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-1.5.2.min.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div class=&quot;container&quot;&gt;
            &lt;?= $sCode ?&gt;
        &lt;/div&gt;
        &lt;?= $sCommentsBlock ?&gt;
        &lt;footer&gt;
            &lt;h2&gt;Creating own commenting system&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/how-to-create-own-commenting-system/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/footer&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><p>By default &#8211; this script will draw list of items. Each item have own page. All easy &#8211; we will display item title, time of adding (&#8216;when&#8217; field), description, and, most important &#8211; our new Comments block. This block contain form of adding new comments, and also will load us last 5 comments. I added my comments in most of places for better understanding. Ok, next PHP file is:</p><h4>comment.php</h4><pre class="brush:php">
&lt;?php
// disabling possible warnings
if (version_compare(phpversion(), &quot;5.3.0&quot;, &quot;&gt;=&quot;)  == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE); 

require_once('classes/CMySQL.php'); // including service class to work with database

$iItemId = (int)$_POST['id']; // obtaining necessary information
$sIp = getVisitorIP();
$sName = $GLOBALS['MySQL']-&gt;escape(strip_tags($_POST['name']));
$sText = $GLOBALS['MySQL']-&gt;escape(strip_tags($_POST['text']));

if ($sName &amp;&amp; $sText) {
    // checking - are you posted any comment recently or not?
    $iOldId = $GLOBALS['MySQL']-&gt;getOne(&quot;SELECT `c_item_id` FROM `s163_items_cmts` WHERE `c_item_id` = '{$iItemId}' AND `c_ip` = '{$sIp}' AND `c_when` &gt;= UNIX_TIMESTAMP() - 600 LIMIT 1&quot;);
    if (! $iOldId) {
        // if all fine - allow to add comment
        $GLOBALS['MySQL']-&gt;res(&quot;INSERT INTO `s163_items_cmts` SET `c_item_id` = '{$iItemId}', `c_ip` = '{$sIp}', `c_when` = UNIX_TIMESTAMP(), `c_name` = '{$sName}', `c_text` = '{$sText}'&quot;);
        $GLOBALS['MySQL']-&gt;res(&quot;UPDATE `s163_items` SET `comments_count` = `comments_count` + 1 WHERE `id` = '{$iItemId}'&quot;);

        // and printing out last 5 comments
        $sOut = '';
        $aComments = $GLOBALS['MySQL']-&gt;getAll(&quot;SELECT * FROM `s163_items_cmts` WHERE `c_item_id` = '{$iItemId}' ORDER BY `c_when` DESC LIMIT 5&quot;);
        foreach ($aComments as $i =&gt; $aCmtsInfo) {
            $sWhen = date('F j, Y H:i', $aCmtsInfo['c_when']);
            $sOut .= &lt;&lt;&lt;EOF
&lt;div class=&quot;comment&quot; id=&quot;{$aCmtsInfo['c_id']}&quot;&gt;
    &lt;p&gt;Comment from {$aCmtsInfo['c_name']} &lt;span&gt;({$sWhen})&lt;/span&gt;:&lt;/p&gt;
    &lt;p&gt;{$aCmtsInfo['c_text']}&lt;/p&gt;
&lt;/div&gt;
EOF;
        }

        echo $sOut;
        exit;
    }
}
echo 1;
exit;

function getVisitorIP() {
    $ip = &quot;0.0.0.0&quot;;
    if( ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) &amp;&amp; ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif( ( isset( $_SERVER['HTTP_CLIENT_IP'])) &amp;&amp; (!empty($_SERVER['HTTP_CLIENT_IP'] ) ) ) {
        $ip = explode(&quot;.&quot;,$_SERVER['HTTP_CLIENT_IP']);
        $ip = $ip[3].&quot;.&quot;.$ip[2].&quot;.&quot;.$ip[1].&quot;.&quot;.$ip[0];
    } elseif((!isset( $_SERVER['HTTP_X_FORWARDED_FOR'])) || (empty($_SERVER['HTTP_X_FORWARDED_FOR']))) {
        if ((!isset( $_SERVER['HTTP_CLIENT_IP'])) &amp;&amp; (empty($_SERVER['HTTP_CLIENT_IP']))) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    }
    return $ip;
}

?&gt;
</pre><p>This file will accept POSTed comments and save them into database. In our project we have another one PHP file:</p><h4>classes/CMySQL.php</h4><p>This is service class to work with database prepared by me. This is nice class which you can use too. Database connection details located in this class in few variables, sure that you will able to configure this to your database. I don`t will publish its sources &#8211; this is not necessary for now. Available in package.</p><h3>Step 3. JS</h3><h4>js/jquery-1.5.2.min.js</h4><p>This is just jQuery library. Available in package.</p><h3>Step 4. CSS</h3><p>Now &#8211; all used CSS styles:</p><h4>css/main.css</h4><pre class="brush:js">
*{
    margin:0;
    padding:0;
}

body {
    background-repeat:no-repeat;
    background-color:#bababa;
    background-image: -webkit-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: -moz-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: -o-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
    min-height:600px;
}

footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}

footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}

footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}

footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

.container {
    border:3px #111 solid;
    color:#000;
    margin:20px auto;
    padding:15px;
    position:relative;
    text-align:center;
    width:500px;

    border-radius:15px;
    -moz-border-radius:15px;
    -webkit-border-radius:15px;
}

#comments form {
    background-color: rgba(255, 255, 255, 0.4);
    margin:10px 0;
    padding:10px;
    text-align:left;
}

#comments table td.label {
    color: #000;
    font-size: 13px;
    padding-right: 3px;
    text-align: right;
    width: 105px;
}

#comments table label {
    color: #000;
    font-size: 16px;
    font-weight: normal;
    vertical-align: middle;
}

#comments table td.field input, #comments table td.field textarea {
    border: 1px solid #96A6C5;
    font-family: Verdana,Arial,sans-serif;
    font-size: 16px;
    margin-top: 2px;
    padding: 6px;
    width: 250px;
}

#comments_list {
    background-color: rgba(255, 255, 255, 0.4);
    margin:10px 0;
    padding:10px;
    text-align:left;
}

#comments_list .comment {
    border-top:1px solid #000;
    padding:10px 0;
}

#comments_list .comment:first-child {
    border-top-width:0px;
}

#comments_list .comment span {
    font-size:11px;
}
</pre><hr
/><h5 style="text-align: center;"><strong><a
title="How to create own commenting system - demo 163" href="http://www.script-tutorials.com/demos/163/index.php" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="How to create own commenting system - package" href="http://www.script-tutorials.com/demos/163/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>Today we prepared great commenting system for your website. Sure that this material will useful for your own projects. Good luck in your work!</p><div
class="shr-publisher-1109"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/how-to-create-own-voting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/155/thumb.png" alt="How to Create Your Own 5 Stars Voting System" /> <br
/> How to Create Your Own 5 Stars Voting System</a></li><li> <a
href="http://www.script-tutorials.com/php-guestbook/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/178/thumb.png" alt="Creating a Diary style PHP Guestbook" /> <br
/> Creating a Diary style PHP Guestbook</a></li><li> <a
href="http://www.script-tutorials.com/creating-own-ajax-poll-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/183/thumb.png" alt="Creating Your Own Ajax Poll System" /> <br
/> Creating Your Own Ajax Poll System</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/how-to-create-own-commenting-system/feed/</wfw:commentRss> <slash:comments>8</slash:comments> </item> <item><title>Autocomplete with PHP, jQuery, MySQL and XML</title><link>http://www.script-tutorials.com/autocomplete-with-php-jquery-mysql-and-xml/</link> <comments>http://www.script-tutorials.com/autocomplete-with-php-jquery-mysql-and-xml/#comments</comments> <pubDate>Tue, 11 Oct 2011 16:35:31 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[autocomplete]]></category> <category><![CDATA[how-to]]></category> <category><![CDATA[js]]></category> <category><![CDATA[tutorial]]></category> <category><![CDATA[xml]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1094</guid> <description><![CDATA[Autocomplete with PHP, jQuery, MySQL and XML Today I have new article for PHP. I will tell you about implementation autocomplete for your sites. Data can be located in different sources &#8211; directly in the JS code, in the database, and even in the XML file. Live Demo download in package Now &#8211; download the [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/easily-interact-between-server-and-client-using-these-jquery-with-ajax-snippets/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="Easily Interact between Server and Client using these jQuery with Ajax Snippets" /> Easily Interact between Server and Client using these jQuery with Ajax Snippets</a></li><li> <a
href="http://www.script-tutorials.com/php-guestbook/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/178/thumb.png" alt="Creating a Diary style PHP Guestbook" /> Creating a Diary style PHP Guestbook</a></li><li> <a
href="http://www.script-tutorials.com/how-to-create-own-commenting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/163/thumb.png" alt="Creating Your Own Commenting System from Scratch" /> Creating Your Own Commenting System from Scratch</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Autocomplete with PHP, jQuery, MySQL and XML" alt="Autocomplete with PHP, jQuery, MySQL and XML" src="http://www.script-tutorials.com/demos/160/thumb.png"></div><p><strong>Autocomplete with PHP, jQuery, MySQL and XML</strong><br
/> <br
/>Today I have new article for PHP. I will tell you about implementation autocomplete for your sites. Data can be located in different sources &#8211; directly in the JS code, in the database, and even in the XML file.<br
/> <span
id="more-1094"></span></p><h5 style="text-align: center;"><strong><a
title="Autocomplete with PHP - demo 160" href="http://www.script-tutorials.com/demos/160/index.html" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Autocomplete with PHP - package" href="http://www.script-tutorials.com/demos/160/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. HTML</h3><p>Here are HTML layout for our autocomplete example page:</p><h4>index.html</h4><pre class="brush:php">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;Autocomplete with PHP, jQuery, MySQL and XML | Script Tutorials&lt;/title&gt;

        &lt;link href=&quot;css/jquery.autocomplete.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-1.5.2.min.js&quot;&gt;&lt;/script&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery.autocomplete.pack.js&quot;&gt;&lt;/script&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/script.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div class=&quot;container&quot;&gt;
            &lt;form action=&quot;#&quot;&gt;
                &lt;p&gt;&lt;label&gt;Your month:&lt;/label&gt; &lt;input id=&quot;month&quot; type=&quot;text&quot; autocomplete=&quot;off&quot;&gt;&lt;/p&gt;
                &lt;p&gt;&lt;label&gt;Your year:&lt;/label&gt; &lt;input id=&quot;year&quot; type=&quot;text&quot; autocomplete=&quot;off&quot;&gt;&lt;/p&gt;
                &lt;p&gt;&lt;label&gt;Your country:&lt;/label&gt; &lt;input id=&quot;country&quot; type=&quot;text&quot; autocomplete=&quot;off&quot;&gt;&lt;/p&gt;
            &lt;/form&gt;
        &lt;/div&gt;
        &lt;footer&gt;
            &lt;h2&gt;Autocomplete with PHP, jQuery, MySQL and XML&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/autocomplete-with-php-jquery-mysql-and-xml/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/footer&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><h3>Step 2. CSS</h3><p>Now, lets define all used styles:</p><h4>css/main.css</h4><pre class="brush:css">
*{
    margin:0;
    padding:0;
}

body {
    background-repeat:no-repeat;
    background-color:#bababa;
    background-image: -webkit-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: -moz-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: -o-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
    min-height:600px;
}

footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}

footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}

footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}

footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

.container {
    border:3px #111 solid;
    color:#000;
    margin:20px auto;
    padding:20px;
    position:relative;
    text-align:center;
    width:300px;

    border-radius:15px;
    -moz-border-radius:15px;
    -webkit-border-radius:15px;
}

.ac_results  {
    border: solid 1px #E5E5E5;
    color:#000;

    border-radius:0 0 5px 5px;
    -moz-border-radius:0 0 5px 5px;
    -webkit-border-radius:0 0 5px 5px;
}
.ac_over {
    background-color:#444;
}

form p {
    margin-bottom:5px;
    text-align:right;
}

form input {
    background-color: #FFFFFF;
    background: -moz-linear-gradient(top, #FFFFFF, #EEEEEE 1px, #FFFFFF 25px);
    background: -webkit-gradient(linear, left top, left 25, from(#FFFFFF), color-stop(4%, #EEEEEE), to(#FFFFFF));
    border: solid 1px #E5E5E5;
    font-size:14px;
    outline: 0;
    padding: 9px;
    width: 180px;

    border-radius:5px;
    -moz-border-radius:5px;
    -webkit-border-radius:5px;

    box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
    -moz-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
    -webkit-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
}

form  input:hover, form  input:focus {
    border-color: #C9C9C9;

    box-shadow: rgba(0,0,0, 0.5) 0px 0px 8px;
    -moz-box-shadow: rgba(0,0,0, 0.5) 0px 0px 8px;
    -webkit-box-shadow: rgba(0,0,0, 0.5) 0px 0px 8px;
}
</pre><p>In our package you can find few more files:</p><h4>css/jquery.autocomplete.css + css/indicator.gif</h4><p>Both files I got from autocomplete jquery package (this is default files &#8211; don`t need to re-publish it in our article)</p><h3>Step 3. Javascript</h3><p>Its time to prepare JS:</p><h4>js/script.js</h4><pre class="brush:js">
$(function(){

    $('#month').autocomplete(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], {
        width: 200,
        max: 3
    });

    $('#year').autocomplete('data.php?mode=xml', {
        width: 200,
        max: 5
    });

    $('#country').autocomplete('data.php?mode=sql', {
        width: 200,
        max: 5
    });

});
</pre><p>As you can see &#8211; very easy syntax of using Autocomplete. In first case I hardcoded possible values directly in JS code. Second and third cases &#8211; through PHP file (using different way of obtaining data &#8211; XML and SQL). In package you can find two another JS files:</p><h4>js/jquery-1.5.2.min.js + js/jquery.autocomplete.pack.js</h4><p>This is jQuery library itself plus Autocomplete plugin</p><h3>Step 4. SQL</h3><p>Now, lets prepare our database &#8211; lets add 1 new table:</p><pre class="brush:sql">
CREATE TABLE `s85_countries` (
  `country_code` varchar(2) NOT NULL,
  `country_name` varchar(255) NOT NULL,
  PRIMARY KEY  (`country_code`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

INSERT INTO `s85_countries` (`country_code`, `country_name`) VALUES
('AR', 'Argentina'),
('AU', 'Australia'),
('BR', 'Brazil'),
('CA', 'Canada'),
('CN', 'China'),
('IN', 'India'),
('KZ', 'Kazakhstan'),
('RU', 'Russia'),
('SD', 'Sudan'),
('US', 'United States');
</pre><p>This small table contain several records &#8211; list of countries. I took that SQL code from one of our old tutorials.</p><h3>Step 5. PHP</h3><p>This step most important &#8211; now you will see how we returning data for Autocomplete:</p><h4>data.php</h4><pre class="brush:php">
&lt;?php

if (version_compare(phpversion(), &quot;5.3.0&quot;, &quot;&gt;=&quot;)  == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE); 

require_once('classes/CMySQL.php');

$sParam = $GLOBALS['MySQL']-&gt;escape($_GET['q']); // escaping external data
if (! $sParam) exit;

switch ($_GET['mode']) {
    case 'xml': // using XML file as source of data
        $aValues = $aIndexes = array();
        $sFileData = file_get_contents('data.xml'); // reading file content
        $oXmlParser = xml_parser_create('UTF-8');
        xml_parse_into_struct($oXmlParser, $sFileData, $aValues, $aIndexes);
        xml_parser_free( $oXmlParser );

        $aTagIndexes = $aIndexes['ITEM'];
        if (count($aTagIndexes) &lt;= 0) exit;
        foreach($aTagIndexes as $iTagIndex) {
            $sValue = $aValues[$iTagIndex]['value'];
            if (strpos($sValue, $sParam) !== false) {
                echo $sValue . &quot;\n&quot;;
            }
        }
        break;
    case 'sql': // using database as source of data
        $sRequest = &quot;SELECT `country_name` FROM `s85_countries` WHERE `country_name` LIKE '%{$sParam}%' ORDER BY `country_code`&quot;;
        $aItemInfo = $GLOBALS['MySQL']-&gt;getAll($sRequest);
        foreach ($aItemInfo as $aValues) {
            echo $aValues['country_name'] . &quot;\n&quot;;
        }
        break;
}
</pre><p>We filter the resulting data by incoming parameter $_GET['q'] from the active text field (where we started typing something). The result &#8211; the script gives all matching records. Another one file which we using (as always):</p><h4>classes/CMySQL.php</h4><p>This is our usual class file to work with database (pretty comfortable). In its constructor you will able to set your own database configuration:</p><pre class="brush:php">
    $this->sDbName = '_DATABASE_NAME_';
    $this->sDbUser = '_DATABASE_USERNAME_';
    $this->sDbPass = '_DATABASE_USERPASS_';
</pre><h3>Step 6. XML</h3><p>Here are content of our XML data file:</p><h4>data.xml</h4><pre class="brush:xml">
<?xml version="1.0"?>
&lt;items&gt;
    &lt;item&gt;1991&lt;/item&gt;
    &lt;item&gt;1990&lt;/item&gt;
    &lt;item&gt;1991&lt;/item&gt;
    &lt;item&gt;1992&lt;/item&gt;
    &lt;item&gt;1993&lt;/item&gt;
    &lt;item&gt;1994&lt;/item&gt;
    &lt;item&gt;1995&lt;/item&gt;
    &lt;item&gt;1996&lt;/item&gt;
    &lt;item&gt;1997&lt;/item&gt;
    &lt;item&gt;1998&lt;/item&gt;
    &lt;item&gt;1999&lt;/item&gt;
    &lt;item&gt;2000&lt;/item&gt;
    &lt;item&gt;2001&lt;/item&gt;
    &lt;item&gt;2002&lt;/item&gt;
    &lt;item&gt;2003&lt;/item&gt;
    &lt;item&gt;2004&lt;/item&gt;
    &lt;item&gt;2005&lt;/item&gt;
    &lt;item&gt;2006&lt;/item&gt;
    &lt;item&gt;2007&lt;/item&gt;
    &lt;item&gt;2008&lt;/item&gt;
    &lt;item&gt;2009&lt;/item&gt;
    &lt;item&gt;2010&lt;/item&gt;
    &lt;item&gt;2011&lt;/item&gt;
    &lt;item&gt;2012&lt;/item&gt;
    &lt;item&gt;2013&lt;/item&gt;
    &lt;item&gt;2014&lt;/item&gt;
    &lt;item&gt;2015&lt;/item&gt;
&lt;/items&gt;
</pre><hr
/><h5 style="text-align: center;"><strong><a
title="Autocomplete with PHP - demo 160" href="http://www.script-tutorials.com/demos/160/index.html" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Autocomplete with PHP - package" href="http://www.script-tutorials.com/demos/160/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>As a result, we see the pattern is obvious &#8211; the fastest way &#8211; when all possible values are hardcoded in JS. In case of XML and SQL &#8211; XML is clearly faster. Just because we even don`t need touch our slow database. I hope that you got interesting lesson for today. Good luck in your work!</p><div
class="shr-publisher-1094"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/easily-interact-between-server-and-client-using-these-jquery-with-ajax-snippets/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="Easily Interact between Server and Client using these jQuery with Ajax Snippets" /> <br
/> Easily Interact between Server and Client using these jQuery with Ajax Snippets</a></li><li> <a
href="http://www.script-tutorials.com/php-guestbook/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/178/thumb.png" alt="Creating a Diary style PHP Guestbook" /> <br
/> Creating a Diary style PHP Guestbook</a></li><li> <a
href="http://www.script-tutorials.com/how-to-create-own-commenting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/163/thumb.png" alt="Creating Your Own Commenting System from Scratch" /> <br
/> Creating Your Own Commenting System from Scratch</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/autocomplete-with-php-jquery-mysql-and-xml/feed/</wfw:commentRss> <slash:comments>21</slash:comments> </item> <item><title>Creating ajaxy Chained Selects with jQuery</title><link>http://www.script-tutorials.com/creating-ajaxy-chained-selects-with-jquery/</link> <comments>http://www.script-tutorials.com/creating-ajaxy-chained-selects-with-jquery/#comments</comments> <pubDate>Mon, 30 May 2011 16:38:43 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[ajaxy]]></category> <category><![CDATA[chained]]></category> <category><![CDATA[selects]]></category> <category><![CDATA[tutorial]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=685</guid> <description><![CDATA[Creating ajaxy chained selects with jQuery Today we will talk about creating dependent (chained) selects for your projects. This can be any related elements at your website. As example dependent fields to select your profession, mobile phone, or location (which can include Country, State, Region etc). One important note &#8211; we will need all this [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/creating-ajaxy-photo-gallery-jquery-with-custom-images-sets/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/136/thumb.png" alt="Creating Ajaxy Photo Gallery (jQuery) with Custom Images Sets" /> Creating Ajaxy Photo Gallery (jQuery) with Custom Images Sets</a></li><li> <a
href="http://www.script-tutorials.com/creating-ajaxy-forums-using-xslt/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/58/thumb.png" alt="How to easily make animated forums using XSLT and Ajaxy" /> How to easily make animated forums using XSLT and Ajaxy</a></li><li> <a
href="http://www.script-tutorials.com/creating-own-ajax-poll-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/183/thumb.png" alt="Creating Your Own Ajax Poll System" /> Creating Your Own Ajax Poll System</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="practice of using chainedSelects" alt="practice of using chainedSelects" src="http://www.script-tutorials.com/demos/85/thumb.png"></div><p><strong>Creating ajaxy chained selects with jQuery</strong><br
/> <br
/>Today we will talk about creating dependent (chained) selects for your projects. This can be any related elements at your website. As example dependent fields to select your profession, mobile phone, or location (which can include Country, State, Region etc). One important note &#8211; we will need all this working using AJAX technology (to make functionality fast and smooth). And, jQuery library provide us with that plugin &#8211; jquery.chainedSelects.js. I will show you how to create chained fields using this plugin.<br
/> <span
id="more-685"></span></p><p>Plugin itself you always can download <a
rel="nofollow" href="http://plugins.jquery.com/project/chained-combobox">here</a>. Ok, here are online demo and downloadable package:</p><h5 style="text-align: center;"><strong><a
title="ajaxy chained selects - chainedSelects - demo 85" href="http://www.script-tutorials.com/demos/85/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="ajaxy chained selects - chainedSelects - demo 85" href="http://www.script-tutorials.com/demos/85/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Ok, download the example files and lets start coding !</p><hr
/><h3>Step 1. SQL</h3><p>We will keep our data in database (tables with countries, states and regions). I don`t will show you FULL sql here (its pretty big), but I will show you structures and few records per table. Full SQL will available in package (check for sql.sql file inside package). As you can see &#8211; I selected prefix &#8216;s85&#8242; for tables &#8211; this is number of our current tutorial. You always can use your own table names if you wish.</p><hr
/><pre class="brush:sql">
-- countries
CREATE TABLE `s85_countries` (
  `country_code` varchar(2) NOT NULL,
  `country_name` varchar(255) NOT NULL,
  PRIMARY KEY  (`country_code`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

INSERT INTO `s85_countries` (`country_code`, `country_name`) VALUES
('AR', 'Argentina'),
('AU', 'Australia'),
('BR', 'Brazil');

-- states
CREATE TABLE `s85_states` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `country_code` varchar(3) NOT NULL,
  `state_name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

INSERT INTO `s85_states` (`id`, `country_code`, `state_name`) VALUES
(1, 'US', 'alabama'),
(2, 'US', 'alaska'),
(3, 'US', 'arizona');

-- regions
CREATE TABLE `s85_regions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `state_id` int(11) NOT NULL,
  `region_name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

INSERT INTO `s85_regions` (`id`, `state_id`, `region_name`) VALUES
(1, 1, 'auburn'),
(2, 1, 'birmingham'),
(3, 1, 'columbus, GA');
</pre><h3>Step 2. PHP</h3><h4>index.php</h4><p>This is our main PHP file, I using this file to generate our FORM with necessary selects for country, state and region fields. And, this file also contain code for ajax calls of states (of selected country) and regions (of selected state).</p><pre class="brush:php">
&lt;?
require_once('classes/CMySQL.php');

if (version_compare(phpversion(), &quot;5.3.0&quot;, &quot;&gt;=&quot;)  == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE); 

// return states of country
if ($_GET['action'] == 'get_states') {
    $sCountryName = $GLOBALS['MySQL']-&gt;escape($_GET['_value']);

    $aRet[] = array(0 =&gt; 'any');
    $aStates = $GLOBALS['MySQL']-&gt;getPairs(&quot;SELECT * FROM `s85_states` WHERE `country_code`='{$sCountryName}'&quot;, 'id', 'state_name');
    foreach ($aStates as $iStateId =&gt; $sStateName) {
        $aRet[] = array($iStateId =&gt; $sStateName);
    }

    echo json_encode($aRet);
    exit;
}
if ($_GET['action'] == 'get_regions') {
    $iStateID = (int)$_GET['_value'];

    $aRet[] = array(0 =&gt; 'any');
    $aRegions = $GLOBALS['MySQL']-&gt;getPairs(&quot;SELECT * FROM `s85_regions` WHERE `state_id`='{$iStateID}'&quot;, 'id', 'region_name');
    foreach ($aRegions as $iRegionId =&gt; $sRegionName) {
        $aRet[] = array($iRegionId =&gt; $sRegionName);
    }

    echo json_encode($aRet);
    exit;
}

$sCountryOptions = '';
$aCountries = $GLOBALS['MySQL']-&gt;getPairs(&quot;SELECT * FROM `s85_countries`&quot;, 'country_code', 'country_name');
foreach ($aCountries as $sCode =&gt; $sName) {
    $sCountryOptions .= '&lt;option value=&quot;'.$sCode.'&quot;&gt;'.$sName.'&lt;/option&gt;';
}
$sCountries = '&lt;select name=&quot;country&quot; id=&quot;country&quot;&gt;'.$sCountryOptions.'&lt;/select&gt;';

echo &lt;&lt;&lt;EOF
&lt;link href=&quot;css/style.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
&lt;script src=&quot;js/jquery.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/jquery.chainedSelects.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/main.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

&lt;div class=&quot;example&quot;&gt;
    &lt;form action=&quot;&quot; method=&quot;post&quot;&gt;
        &lt;div&gt;&lt;label for=&quot;country&quot;&gt;Country&lt;/label&gt;{$sCountries}&lt;/div&gt;
        &lt;div&gt;&lt;label for=&quot;state&quot;&gt;State&lt;/label&gt;
            &lt;select name=&quot;state&quot; id=&quot;state&quot;&quot;&gt;&lt;option value=&quot;0&quot;&gt;any&lt;/option&gt;&lt;/select&gt;
        &lt;/div&gt;
        &lt;div&gt;&lt;label for=&quot;region&quot;&gt;Region&lt;/label&gt;
            &lt;select name=&quot;region&quot; id=&quot;region&quot;&quot;&gt;&lt;option value=&quot;0&quot;&gt;any&lt;/option&gt;&lt;/select&gt;
        &lt;/div&gt;
        &lt;div&gt;&lt;input name=&quot;submit&quot; type=&quot;submit&quot; value=&quot;Send this info&quot; /&gt;&lt;/div&gt;
    &lt;/form&gt;
&lt;/div&gt;
EOF;

if ($_POST) {
    // draw debug information
    echo '&lt;pre&gt;';
    print_r($_POST);
    echo '&lt;/pre&gt;';
}

?&gt;
</pre><p>Make attention, I using my own class for work with database &#8211; &#8216;classes/CMySQL.php&#8217;. This file already available in package. Commonly &#8211; you can use same, or similar class for your own projects. This just give some comfort with working with database. One thing what you will need to do &#8211; configure database connection params inside that file (in top of its code).</p><h3>Step 3. JS</h3><h4>js/jquery.js and js/jquery.chainedSelects.js</h4><p>This is just ordinary jQuery library with our new plugin &#8211; chainedSelects. Both files available in package.</p><h4>js/main.js</h4><pre class="brush:js">
$(function() {
  $('select[name=country]').chainSelect('#state','index.php?action=get_states', {
    before:function (target) {
      $(target).css('visibility','hidden');
    },
    after:function (target) {
      $(target).css('visibility','visible');
    }
  });
  $('#state').chainSelect('#region','index.php?action=get_regions', {
    before:function (target) {
      $(target).css('visibility','hidden');
    },
    after:function (target) {
      $(target).css('visibility','visible');
    }
  });
});
</pre><p>Syntax of chainedSelects using easy, we can point which URL will called when we changing selects, also we can perform some extra actions before request, and after.</p><h3>Step 4. CSS</h3><h4>css/style.css</h4><pre class="brush:css">
body {
    background:#eee;
    margin:0;
    padding:0;
}
.example {
    background:#FFF;
    width:400px;
    border:1px #000 solid;
    margin:20px auto;
    padding:15px;
    -moz-border-radius:3px;
    -webkit-border-radius:3px;
}
.example form {
    background:#EEE;
    border:1px #DDD solid;
    padding:10px;
    -moz-border-radius:3px;
    -webkit-border-radius:3px;
}
.example form div {
    margin:10px;
}
.example form div label {
    display:block;
    width:100px;
    float:left;
}
.example form div select {
    width:200px;
}
</pre><hr
/><h5 style="text-align: center;"><strong><a
title="ajaxy chained selects - chainedSelects - demo 85" href="http://www.script-tutorials.com/demos/85/index.php" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="ajaxy chained selects - chainedSelects - demo 85" href="http://www.script-tutorials.com/demos/85/source.zip" target="_blank" rel="nofollow">download in package</a></strong></h5><hr
/><h3>Conclusion</h3><p>In result, now we have pretty nice dependent selectors where we can choose our location. Happy coding. Good luck in your projects!</p><div
class="shr-publisher-685"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/creating-ajaxy-photo-gallery-jquery-with-custom-images-sets/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/136/thumb.png" alt="Creating Ajaxy Photo Gallery (jQuery) with Custom Images Sets" /> <br
/> Creating Ajaxy Photo Gallery (jQuery) with Custom Images Sets</a></li><li> <a
href="http://www.script-tutorials.com/creating-ajaxy-forums-using-xslt/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/58/thumb.png" alt="How to easily make animated forums using XSLT and Ajaxy" /> <br
/> How to easily make animated forums using XSLT and Ajaxy</a></li><li> <a
href="http://www.script-tutorials.com/creating-own-ajax-poll-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/183/thumb.png" alt="Creating Your Own Ajax Poll System" /> <br
/> Creating Your Own Ajax Poll System</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/creating-ajaxy-chained-selects-with-jquery/feed/</wfw:commentRss> <slash:comments>4</slash:comments> </item> <item><title>How to easily make animated forums using XSLT and Ajaxy</title><link>http://www.script-tutorials.com/creating-ajaxy-forums-using-xslt/</link> <comments>http://www.script-tutorials.com/creating-ajaxy-forums-using-xslt/#comments</comments> <pubDate>Fri, 15 Apr 2011 17:18:49 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[XSLT]]></category> <category><![CDATA[ajaxy]]></category> <category><![CDATA[animated]]></category> <category><![CDATA[creating]]></category> <category><![CDATA[forums]]></category> <category><![CDATA[making]]></category> <category><![CDATA[xslt]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=529</guid> <description><![CDATA[How to easily make animated forums using XSLT and Ajaxy Today is a special day. Today our XSLT lessons will show some really interesting (attractive) results which you can apply in practice. We will make a forum. Initially we will display only the forum topics, and load posts dynamically (by mouse clicking on the topics) [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/how-to-easily-display-stumbleupon-posts-using-xslt-transformation/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to Easily display Your Stumbleupon Favorites using XSLT" /> How to Easily display Your Stumbleupon Favorites using XSLT</a></li><li> <a
href="http://www.script-tutorials.com/how-to-easily-display-twitter-posts-using-xslt-transformation/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to Easily display Your Tweets using XSLT transformation" /> How to Easily display Your Tweets using XSLT transformation</a></li><li> <a
href="http://www.script-tutorials.com/how-to-easily-display-delicious-bookmarks-using-xslt/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/47.png" alt="How to Easily display Delicious bookmarks using XSLT transformation" /> How to Easily display Delicious bookmarks using XSLT transformation</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Ajaxy forum using XSLT" alt="Ajaxy forum using XSLT" src="http://www.script-tutorials.com/demos/58/thumb.png"></div><p><strong>How to easily make animated forums using XSLT and Ajaxy</strong><br
/> <br
/>Today is a special day. Today our XSLT lessons will show some really interesting (attractive) results which you can apply in practice. We will make a forum. Initially we will display only the forum topics, and load posts dynamically (by mouse clicking on the topics) using ajax technology. I think you may have seen similar forums on the Internet, so I will tell you how to do it your own.<br
/> <span
id="more-529"></span></p><p>Here are samples and downloadable package:</p><h5 style="text-align: center;"><strong><a
title="Creating animated forums using XSLT - demo 58" href="http://www.script-tutorials.com/demos/58/index.php" target="_blank">Forum Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Creating animated forums using XSLT - demo 58" href="http://www.script-tutorials.com/demos/58/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Ok, download the source files and lets start coding !</p><hr
/><h3>Step 1. Source XML</h3><p>Firstly lets define our structure of forum:</p><h4>forum.xml</h4><pre class="brush:xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;forum&gt;
    &lt;topic title=&quot;XSLT forum demonstration&quot; date=&quot;15.04.2011&quot; description=&quot;description can be here&quot;&gt;
        &lt;post date=&quot;15.04.2011&quot; author=&quot;Diego&quot;&gt;
            &lt;description&gt;&lt;![CDATA[
            This forum able to display any HTML entities
            ]]&gt;&lt;/description&gt;
        &lt;/post&gt;
        &lt;post date=&quot;15.04.2011&quot; author=&quot;Andrew&quot;&gt;
            &lt;description&gt;&lt;![CDATA[
            As example &lt;b&gt;bold text&lt;/b&gt;, &lt;i&gt;italic&lt;/i&gt;, &lt;u&gt;underline&lt;/u&gt;, &lt;a href=&quot;http://www.google.com&quot;&gt;links&lt;/a&gt; etc
            ]]&gt;&lt;/description&gt;
        &lt;/post&gt;
        &lt;post date=&quot;15.04.2011&quot; author=&quot;James&quot;&gt;
            &lt;description&gt;&lt;![CDATA[
            &lt;p&gt;Some HTML description 3, &lt;a href=&quot;http://www.google.com&quot;&gt;links&lt;/a&gt; etc
            ]]&gt;&lt;/description&gt;
        &lt;/post&gt;
        &lt;post date=&quot;15.04.2011&quot; author=&quot;John&quot;&gt;
            &lt;description&gt;&lt;![CDATA[
            Hello guys here
            ]]&gt;&lt;/description&gt;
        &lt;/post&gt;
        &lt;post date=&quot;15.04.2011&quot; author=&quot;Robert&quot;&gt;
            &lt;description&gt;&lt;![CDATA[
            Wonderful forum, isn`t it?
            ]]&gt;&lt;/description&gt;
        &lt;/post&gt;
    &lt;/topic&gt;
    &lt;topic title=&quot;sample forum topic 2&quot; date=&quot;16.04.2011&quot; description=&quot;description of topic 2&quot;&gt;
        &lt;post date=&quot;16.04.2011&quot; author=&quot;Michael&quot;&gt;
            &lt;description&gt;&lt;![CDATA[
            sample record 1
            ]]&gt;&lt;/description&gt;
        &lt;/post&gt;
        &lt;post date=&quot;16.04.2011&quot; author=&quot;William&quot;&gt;
            &lt;description&gt;&lt;![CDATA[
            sample record 2
            ]]&gt;&lt;/description&gt;
        &lt;/post&gt;
        &lt;post date=&quot;16.04.2011&quot; author=&quot;David&quot;&gt;
            &lt;description&gt;&lt;![CDATA[
            sample record 3
            ]]&gt;&lt;/description&gt;
        &lt;/post&gt;
    &lt;/topic&gt;
    &lt;topic title=&quot;sample forum topic 3&quot; date=&quot;17.04.2011&quot; description=&quot;description of topic 3&quot;&gt;
        &lt;post date=&quot;17.04.2011&quot; author=&quot;Charles&quot;&gt;
            &lt;description&gt;&lt;![CDATA[
            sample record 3.1
            ]]&gt;&lt;/description&gt;
        &lt;/post&gt;
        &lt;post date=&quot;17.04.2011&quot; author=&quot;Joseph&quot;&gt;
            &lt;description&gt;&lt;![CDATA[
            sample record 3.2
            ]]&gt;&lt;/description&gt;
        &lt;/post&gt;
    &lt;/topic&gt;
&lt;/forum&gt;
</pre><p>Forum contain several topics, each topic can contain variable amount of posts. Each post have name of Author, date of posting, and, text itself (Description) can contain HTML tags.</p><h3>Step 2. PHP</h3><p>Here are easy PHP file which we using for xsl transformation:</p><h4>index.php</h4><pre class="brush:php">
&lt;?php

if (version_compare(phpversion(), &quot;5.3.0&quot;, &quot;&gt;=&quot;)  == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE); 

// create DomDocument and load our forum
$xml = new DOMDocument;
$xml-&gt;load('forum.xml');

$xsl = new DOMDocument;

switch ($_POST['action']) {
    case 'posts':
        $xsl-&gt;load('xslt/posts.xslt'); // importing xslt
        $proc = new XSLTProcessor; // creating xslt processor
        $proc-&gt;importStyleSheet($xsl); // attaching xsl rules
        $proc-&gt;setParameter('', 'topic_id', (int)$_POST['i']); // we will set param for XSL
        break;
    default:
        $xsl-&gt;load('xslt/forum.xslt'); // importing xslt
        $proc = new XSLTProcessor; // creating xslt processor
        $proc-&gt;importStyleSheet($xsl); // attaching xsl rules
        break;
}

echo $proc-&gt;transformToXML($xml); // output

?&gt;
</pre><p>Make attention to switch-case. For ajax response (when we clicking to our topics) I using first switch case (when action = posts). To determine which messages we will display (filter) I will pass ID of topic (topic_id) to our XSL script.</p><h3>Step 3. CSS</h3><p>Here are used CSS file:</p><h4>css/styles.css</h4><pre class="brush:css">
body{background:#eee;font-family:Verdana, Helvetica, Arial, sans-serif;margin:0;padding:0}
.main{background:#FFF;width:698px;min-height:500px;overflow:hidden;border:1px #000 solid;margin:3.5em auto 2em;padding:1em 2em 2em}

p{margin:0;padding:0}
.forum{border:1px solid #B0BBCD}
.forum .header{color:#fff;background-color:#545F6F;padding:5px}
.forum .topic{border-bottom:2px solid #B0BBCD;background-color:#F3F2EF;padding:5px}
.forum .topic .desc{margin-left:30px;font-size:12px;color:#444}
.forum .topic .posts{border-top:1px solid #B0BBCD;display:none;margin-top:10px;padding:10px}
.forum .topic .posts .post{border-bottom:1px solid #B0BBCD;margin:5px}
.forum .post .date{font-size:10px;color:#444;text-align:right}
</pre><p>Here are several styles of our forum &#8211; styles for topics, posts etc.</p><h3>Step 4. JS</h3><p>Here are used JS files:</p><h4>js/jquery.min.js</h4><p>This is just jQuery library, available in package.</p><h4>js/main.js</h4><pre class="brush:js">
function loadPosts(obj, i) {
    $('.topic#'+i+' .posts').load('index.php',
      {action: 'posts', i: i},
      function() {
        $(this).fadeIn('slow');

        obj.unbind('click');
        obj.click(function(e) {
            $('.topic#'+i+' .posts').slideToggle('slow');
        });
      }
    );
}

$(function(){
    $('.topic').click(function() {
        loadPosts( $(this), $(this).attr('id') );
    });
});
</pre><p>When page loaded &#8211; I linking onClick events to our forum topics. After, when we clicking to Topic element, I using $.load to load posts of this Topic. And, unbind old onClick functional (we don`t will need to load this content twice), and adding new onClick event, which will toggle slide of these posts.</p><h3>Step 5. XSLT</h3><p>And, the delicacy &#8211; used XSLT rules:</p><h4>xslt/forum.xslt</h4><pre class="brush:xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt;
    &lt;xsl:output method=&quot;html&quot; doctype-system=&quot;http://www.w3.org/TR/html4/strict.dtd&quot; doctype-public=&quot;-//W3C//DTD HTML 4.01//EN&quot; indent=&quot;yes&quot; /&gt;
    &lt;xsl:template match=&quot;/&quot;&gt;
        &lt;html xml:lang=&quot;en&quot;&gt;
            &lt;head&gt;
                &lt;script src=&quot;js/jquery.min.js&quot; type=&quot;text/javascript&quot;&gt;&gt;&lt;/script&gt;
                &lt;script src=&quot;js/main.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
                &lt;link media=&quot;all&quot; href=&quot;css/styles.css&quot; type=&quot;text/css&quot; rel=&quot;stylesheet&quot;/&gt;
                &lt;title&gt;Our XSLT-based ajaxy forum&lt;/title&gt;
            &lt;/head&gt;
            &lt;body&gt;
                &lt;div class=&quot;main&quot;&gt;
                    &lt;h2&gt;Our XSLT-based ajaxy forum&lt;/h2&gt;
                    &lt;div class=&quot;forum&quot;&gt;
                        &lt;div class=&quot;header&quot;&gt;Forum topics&lt;/div&gt;
                        &lt;xsl:for-each select=&quot;forum/topic&quot;&gt;
                            &lt;div class=&quot;topic&quot;&gt;
                                &lt;xsl:attribute name=&quot;id&quot;&gt;
                                    &lt;xsl:value-of select=&quot;position()&quot;/&gt;
                                &lt;/xsl:attribute&gt;

                                &lt;a class=&quot;top_link&quot; href=&quot;javascript:void(0)&quot;&gt;
                                    &lt;xsl:value-of select=&quot;@title&quot;/&gt; (&lt;xsl:value-of select=&quot;count(child::*)&quot;/&gt;)
                                &lt;/a&gt;
                                &lt;div class=&quot;desc&quot;&gt;
                                    &lt;xsl:value-of select=&quot;@description&quot;/&gt;
                                &lt;/div&gt;
                                &lt;div class=&quot;posts&quot;&gt;&lt;/div&gt;
                            &lt;/div&gt;
                        &lt;/xsl:for-each&gt;

                    &lt;/div&gt;
                &lt;/div&gt;
                &lt;xsl:comment&gt;Copyright: AndrewP&lt;/xsl:comment&gt;
            &lt;/body&gt;
        &lt;/html&gt;
    &lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;
</pre><p>As you can see, here we generating our main forum, and drawing only topics now. We will load posts ajaxy fr each Topic using jQuery, nice, isn`t is?</p><h4>xslt/posts.xslt</h4><pre class="brush:xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt;
    &lt;xsl:template match=&quot;/&quot;&gt;
        &lt;xsl:for-each select=&quot;forum/topic[position() = $topic_id]/*&quot;&gt;
            &lt;div class=&quot;post&quot;&gt;
                &lt;xsl:attribute name=&quot;id&quot;&gt;
                    &lt;xsl:value-of select=&quot;position()&quot;/&gt;
                &lt;/xsl:attribute&gt;
                &lt;xsl:value-of select=&quot;description&quot; disable-output-escaping=&quot;yes&quot;/&gt;
                &lt;div class=&quot;date&quot;&gt;
                    posted at &lt;xsl:value-of select=&quot;@date&quot;/&gt; by &lt;xsl:value-of select=&quot;@author&quot;/&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/xsl:for-each&gt;
    &lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;
</pre><p>Second XSL file we will use to generate list of posts for requested Topic. Hope that you don`t forget that we will request it ajaxy? We already passed $topic_id variable into this XSL above (in PHP code). So, we just should display all child &#8216;posts&#8217; of our Topic.</p><hr
/><h5 style="text-align: center;"><strong><a
title="Creating animated forums using XSLT - demo 58" href="http://www.script-tutorials.com/demos/58/index.php" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Creating animated forums using XSLT - demo 58" href="http://www.script-tutorials.com/demos/58/source.zip" target="_blank" rel="nofollow">download in package</a></strong></h5><hr
/><h3>Conclusion</h3><p>I hope that today&#8217;s article was very interesting, and I hope that interest to XSL language has not dried up <img
src='http://www.script-tutorials.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> Good luck!</p><div
class="shr-publisher-529"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/how-to-easily-display-stumbleupon-posts-using-xslt-transformation/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to Easily display Your Stumbleupon Favorites using XSLT" /> <br
/> How to Easily display Your Stumbleupon Favorites using XSLT</a></li><li> <a
href="http://www.script-tutorials.com/how-to-easily-display-twitter-posts-using-xslt-transformation/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to Easily display Your Tweets using XSLT transformation" /> <br
/> How to Easily display Your Tweets using XSLT transformation</a></li><li> <a
href="http://www.script-tutorials.com/how-to-easily-display-delicious-bookmarks-using-xslt/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/47.png" alt="How to Easily display Delicious bookmarks using XSLT transformation" /> <br
/> How to Easily display Delicious bookmarks using XSLT transformation</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/creating-ajaxy-forums-using-xslt/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: basic (User agent is rejected)
Database Caching using disk: basic

Served from: www.script-tutorials.com @ 2012-02-04 21:49:08 -->
