In this tutorial I will cover the simple concept of making a global shoutbox in a website. This tutorial covers basics and some nice features.
Let's go over the method we have in mind first, so you're not completely lost when doing this for yourself.
We are going to use AJAX and MySQL. For those of you who don't know, AJAX (Asynchronous JavaScript and XML) is JavaScript + PHP or ASP. I will be using PHP.
MySQL- databases. Yes, we are going to store all of these messages in a database.
DATABASE
Let's start with the database. You need to make a new table that holds all the shoutbox information. For mine, I will use four simple parameters (you can add more to yours if you feel like it's necessary):
ID - Primary key. Integer of (default) 11 digits. You can make this smaller or larger if you want. Auto-increments.
Poster - Who was the message posted by? I use a varchar of 20 characters.
Time - The time of the post. This is going to be a timestamp. The default syntax is YYYY-MM-DD HH:MM:SS. You can parse this yourself later, if you want.
Message - text. The message itself.
So, the MySQL would look something like this:
CREATE TABLE `shoutbox` ( `id` INT NOT NULL AUTO_INCREMENT , `poster` VARCHAR( 20 ) NOT NULL , `message` TEXT NOT NULL , `time` TIMESTAMP NOT NULL , PRIMARY KEY ( `id` ) )
The HTML
Let's put together a simple HTML form, assuming the user is already logged in and can post.
<html> <head> <title>Shoutbox</title> </head> <body onload="updateShoutbox()"> <div id="shoutbox"> </div> Message:<input type="text" id="message" /><input type="button" onclick="postMsg()" /> </body> </html>Simple, you can add some styles or whatever to make it more interesting. Notice I call two JavaScript functions. We're going to make those presently.
OK, easy part done. Now, let's talk about the method of actually making the shoutbox work.
Since there is no way (as of yet) to get something to a browser as soon as it is written in, we need to check to see if there are any new posts every so often.
This is quite ineffective, really (if you imagine going to the post office every hour to check your mail instead of the mailman bringing it to you, its kinda like that), but there's no other way to do it.
You want an increment that is low enough so that users can actually have a chat, but not so much that it slows down and crashes the browser. This varies from domain to domain, we we'll worry about this later.
CLIENT SIDE SCRIPT
Now for the AJAX functions. You're going to need just 2, and that is to just check updates and post it.
There are actually a few ways to do this, and you can pick which one would be more efficient for your needs.
You can:
a) Check to see if any NEW posts were made (involve much checking) and only post NEW posts.
I'm going to do B, since it won't slow down the browser and I don't have to make code for checking time.
NOTE: These functions should go in the head.
OK, here's the basic function for getting the XMLHttp Object:
<script type="text/javascript">
function GetXmlHttpObject(){
if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject){// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
Now, let's make the update shoutbox function. <script type="text/javascript">
var xmlhttp1;
function updateShoutbox(){
xmlhttp1=GetXmlHttpObject();
if (xmlhttp1==null){
alert ("Browser does not support HTTP Request");
return;
}
var url="update.php";
xmlhttp1.onreadystatechange=function(){
if(xmlhttp1.readyState==4){
document.getElementById("shoutbox").innerHTML=xmlhttp1.responseText;
}
};
xmlhttp1.open("GET",url,true);
xmlhttp1.send(null);
var x = setTimeout(function(){ updateShoutbox(); },1000); //Checks for new posts every second. Remember, it's in milliseconds. Change as necessary.
}
</script>
And finally, the script for posting.
<script type="text/javascript">
var xmlhttp2;
var username = "Some guy"; //Replace this with username by using PHP.
function postMsg(){
xmlhttp2=GetXmlHttpObject();
if (xmlhttp2==null){
alert ("Browser does not support HTTP Request");
return;
}
var url="post.php?user="+username+"&msg="+document.getElementById("message").value;
xmlhttp2.open("GET",url,true);
xmlhttp2.send(null);
}
</script>
Notice for the username I put in "Some guy". You're supposed to replace this with the username by using PHP, like:var username = "<?php echo $username; ?>";
And that's all the client side script we need.
SERVER SIDE SCRIPT
We need 2 different PHP scripts, post.php and update.php.
Let's start with update. We need to get up to a certain amount of posts. Let's just say its 20. Your script should look something like:
Note: I'm assuming you've already connected to your database.
<?php
//Connect to your database first.
$query = "SELECT COUNT(*) FROM shoutbox";
$q = mysql_query($query); //Get the total amount of posts. EVAR.
$total = mysql_fetch_row($q);
$total = $total[0];
$posts_returned = 20; //alter as you see fit.
//use a loop to get the posts.
for($i=($total-$posts_returned);$i<=$total;$i++){
$query = "SELECT * FROM shoutbox WHERE id=".$i; //Get the corresponding message.
$q = mysql_query($query);
$msg = mysql_fetch_array($q);
//Format as you see fit.
echo "<span style='color:gray;font-weight:bold'>";
echo $msg['poster'];
echo "</span>";
echo $msg['message'];
echo "(Posted at ".$msg['time'].")";
echo "<br />";
}
?>
You can add whatever you want to here, make it fancier, yeah yeah.
Moving on to post.php, which is going to take 2 parameters: the user who posted it, and the message.
//Again, assuming you've already connected to the database.
$poster = $_GET['user'];
$message = $_GET['msg'];
$query = "INSERT INTO shoutbox (poster,message) VALUES ('".$poster."','".$message."')"; //We only need to deal with these two. The others will fill themselves in.
//Important: remember the single quotes around poster and message.
mysql_query($query);
And that should be it. Note: this was written by me, but not tested. Please post any problems you may have, and enjoy!















