In this tutorial i’ll show how to create a simple shoutbox mootools script that is based from other existing shoutbox on the net.
Features of simple mootools shoutbox:
Lets start with the database first.
We will create a new database named shoutbox, create a table named log with four fields: id, name of the poster, message of the poster and the date the post was created.
Below is the table structure for table log.
CREATE TABLE IF NOT EXISTS `log` ( `id` int(11) NOT NULL auto_increment, `name` varchar(50) NOT NULL, `message` varchar(175) NOT NULL, `date_created` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Create a html file. Add the code below inside the body.
On line 1 with <div id=”shoutboard”></div>indicates the container where the last previous posts will appear.
<div id="shoutboard"></div>
<input id="name" type="text" />
<input id="message" type="text" />
<button id="post">Post</button>
Now lets take a look at the javascript.
There are only four functions used in the javascript. They are postShoutout, loadExistingData, loadData and generateMessage.
Lets discuss first the postShoutout function.
postShoutout function passes the posted values to shout.php script. Once the posted values are saved successfully, postShoutout will create a new div element and set the posted value as its value. It will append the newly created element at the end of shoutboard div.
On lines 13-15, if the entries are more than 15, the first entry will be removed from the page. It is done by counting the children of shoutboard div then disposing the first entry if the entries reached a maximum number of 15 posts.
The postShoutout function.
var postShoutout = function() {
$('post').addEvent( 'click' , function(){
if( $('message').value == '' ) {
$('message').setStyle('border', '1px solid #CC0000');
}
if( ( $('message').value != '' ) &&
( $('name').value != '' ) ) {
var request = new Request.JSON({
url: 'shout.php',
onSuccess: function(jsonObj) {
if (jsonObj.status == 'true') {
if($('shoutboard').getChildren().length == 15) {
$('shoutboard').getFirst('div').dispose();
}
var el = new Element(
'div',
{
'html': $('name').value
+ ': '
+ $('message').value
}
);
el.inject($('shoutboard'));
$('message').set('value', '');
}
}}).get({
'name' : $('name').value,
'message' : $('message').value
});
}
});
};
The loadExistingData and loadData does two things. Creates a new Element and sets the server reponse inside the element. The only difference is that loadData periodically loads new data from the server so new posts from other visitors will be seen by the current user.
var loadExistingData = function() {
var request = new Request.JSON({
url: 'load.php',
onSuccess: function(jsonObj) {
if (jsonObj.status == 'true') {
generateMessage(jsonObj.loadnow);
}
}}).get({});
};
var loadData = function() {
var request = new Request.JSON({
url: 'load.php',
onSuccess: function(jsonObj) {
if (jsonObj.status == 'true') {
$('shoutboard').set('html', '');
generateMessage(jsonObj.loadnow);
}
}}).get();
};
When loading data, generateMessage function creates new elements for every post.
var generateMessage = function(jobj) {
jobj.each(function(messages) {
var el = new Element('div', {'html': messages.message});
el.inject($('shoutboard'));
});
};
The load and domready events.
window.addEvents({
'load' : function(){
loadExistingData();
loadData.periodical(2000);
},
'domready' : function(){
postShoutout();
$('name').addEvents({
focus : function(){
$('name').set('value', '');
},
blur : function() {
if($('name').value == '') {
$('name').set('value', 'Nickname');
}
}
});
$('message').addEvents({
focus : function(){
$('message').set('value', '');
},
blur : function() {
if($('message').value == '') {
$('message').set('value', 'Message');
}
}
});
}
});
Lastly, the php code that will handle the requests.
Below is the shout.php. It stores the posted values in the database. It will return true for successful storing of data otherwise, false.
$name = $_GET['name']; $message = $_GET['message']; $query = mysql_query( "INSERT INTO log ( name, message, date_created ) VALUES ( '$name', '$message', NOW() )" ) or die(mysql_error()); header( "Content-type: application/json" ); $result = ( $query ) ? array( "status" => "true" ) : array( "status" => "false" ) ; echo json_encode( $result );
The load.php process the periodical request of the function loadData
$query = mysql_query( "SELECT name, message FROM log ORDER BY id DESC LIMIT 15" ) or die(mysql_error());
if(mysql_num_rows( $query ) != 0)
{
while( $row = mysql_fetch_array( $query ) )
{
$html[] = array( "message" => $row['name'] . ': ' . $row['message'] );
}
krsort($html);
foreach( $html as $value )
{
$sorted_value[] = $value;
}
$array = array( "status" => "true", "loadnow" => $sorted_value ) ;
}
else
{
$array = array( "status" => "false" );
}
header( "Content-type: application/json" );
echo json_encode($array);
One Comment
8:34 am on September 30th, 2010:
Very good tutorial. Thanks. It really helped me =)
Leave a Reply