Dynamic ajax based shoutbox with jQuery from scratch. It will be very interesting to know how to use the ajax function of jQuery and how it can be used to insert and recover data from a MySQL database via PHP in a way asynchronous.
Step 1: The Layout
First of all we will create the layout (as always, you know), it will be similar to the tabbed menu tutorial and it will have 2 main divisions:
* Form (fields with the user and message to send)
* Container division (contains the messages)
* Loading division (as a part of the Container division, displays the loading animated gif… while messages are loading)
So now we have have seen the main divisions, take a look at the xHTML code:
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>yensdesign.com - Create a shoutbox using PHP and AJAX with jQuery</title> <link rel="stylesheet" href="css/general.css" type="text/css" media="screen" /> </head> <body> <a id="logo" title="Go to yensdesign.com!" href="http://www.yensdesign.com"><img src="css/images/logo.jpg" alt="yensdesign.com" /></a> <form method="post" id="form"> <table> <tr> <td><label>User</label></td> <td><input class="text user" id="nick" type="text" MAXLENGTH="25" /></td> </tr> <tr> <td><label>Message</label></td> <td><input class="text" id="message" type="text" MAXLENGTH="255" /></td> </tr> <tr> <td></td> <td><input id="send" type="submit" value="Shout it!" /></td> </tr> </table> </form> <div id="container"> <ul class="menu"> <li>Shoutbox</li> </ul> <span class="clear"></span> <div class="content"> <h1>Latest Messages</h1> <div id="loading"><img src="css/images/loading.gif" alt="Loading..." /></div> <ul> </ul><ul> </ul></div> </div> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="shoutbox.js"></script> </body> </html>
We are limiting the maxlength of both fields: nick(25) & message(255) because our shoutbox table will have these length limitations.
Nothing more to explain over here, let's go to the CSS part.
Step 2: Adding some style with CSS
There is nothing special in this case for the css part, just remember you that we are reusing the CSS trick for the tab that we have used in the tabbed menu tutorial.
Here you have the entire CSS code:
@CHARSET "UTF-8"; /******* GENERAL RESET *******/ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { border:0pt none; font-family:inherit; font-size: 100%; font-style:inherit; font-weight:inherit; margin:0pt; padding:0pt; vertical-align:baseline; } body{ background: #fff; line-height:14px; font-size: 12px; font-family: Arial, Verdana, Helvetica, sans-serif; margin:0pt; cursor:default; overflow: hidden; } html,body{ height:100%; text-align: center; } .clear{ clear: both; height: 0; visibility: hidden; display: block; } a{ text-decoration: none; } strong{ font-weight: 700; } /******* GENERAL RESET *******/ /******* LOGO *******/ #logo{ margin-top: 1em; display: block; } /******* /LOGO *******/ /******* FORM *******/ #form{ margin: 5em auto 3em; width: 300px; } #form table td{ text-align: left; font-size: 11px; } #form label{ font-weight: 700; } #form input{ border: 1px solid #d0ccc9; background: #fff; color: #5f95ef; font-size: 11px; font-weight: 700; } #form input.text{ font-weight: normal; color: #565656; border: 1px solid #9c9c9c; width: 250px; padding: 2px; margin-bottom: 5px; text-align: left; } #form input.text.user{ width: 100px; } /******* /FORM *******/ /******* MENU *******/ #container{ margin: 1em auto; width: 400px; } #container ul{ list-style: none; list-style-position: outside; } #container ul.menu li{ float: left; margin-right: 5px; margin-bottom: -1px; } #container ul.menu li{ font-weight: 700; display: block; padding: 5px 10px 5px 10px; background: #fff; border: 1px solid #d0ccc9; border-width: 1px 1px 0 1px; position: relative; color: #5f95ef; cursor: pointer; } /******* /MENU *******/ /******* CONTENT *******/ .content{ margin: 0pt auto; background: #efefef; background: #fff; border: 1px solid #d0ccc9; text-align: left; padding: 10px; padding-bottom: 20px; font-size: 11px; } .content h1{ line-height: 1em; vertical-align: middle; height: 48px; padding: 10px 10px 10px 52px; font-size: 32px; background: transparent url(images/bubble.jpg) no-repeat scroll left top; } .date{ font-weight: normal; font-size: 9px; color: #aeaeae; } /******* /CONTENT *******/ /******* LOADING *******/ #loading{ text-align: center; } /******* /LOADING *******/
As you may noticed, we have an empty ul element with no li elements, that's because we will load his content via AJAX
Let's create the MySQL table.
Step 3: Creating shoutbox table in MySQL
As I told you, we will make use of a MySQL database to store our messages and then we will retrieve data via PHP. So we only need to create a simple table called shoutbox with these columns:
* id (int primary key and with auto increment)
* date (timestamp default CURRENT_TIMESTAMP)
* user (varchar 25)
* message (varchar 255)
So here you have the MySQL code that you must execute in your database (via phpmyadmin for example):
CREATE TABLE `shoutbox`( `id` int(5) NOT NULL auto_increment, `date` timestamp NOT NULL default CURRENT_TIMESTAMP, `user` varchar(25) NOT NULL default 'anonimous', `message` varchar(255) NOT NULL default '', PRIMARY KEY (`id`) );
So now that we have our layout ready and the MySQL table created let's continue with the PHP part.
Step 4: Using PHP to insert & recover data from MySQL database
Last two steps (step 4 & step 5) are very important so guys pay attention! With jQuery.ajax() function from jQuery we can load a remote page using an HTTP request.
We will make use of the jQuery.ajax() function to make a POST request to a PHP script named shoutbox.php that will manage the insert / retrieve data action with a switch sentence. We will receive a XMLHttpRequest object from $.ajax() function that will have a property called responseText. This property will give us the required information to display the shoutbox's messages (in case of select action) or the confirmation (in case of insert action).
So before add the AJAX code we need to create our shoutbox.php that will manage all the requests from our future javascript file shoutbox.js. We will define some constants to the MySQL connection:
/************************ CONSTANTS /************************/ define("HOST", "YOUR HOST"); define("USER", "YOUR USER"); define("PASSWORD", "YOUR USER PASSWORD"); define("DB", "YOUR DATABASE");
As you may noticed the second parameter of each define() function it's wrong / empty, you must change them for values that apply in your case.
Now we have defined our constants to the connection with MySQL we will create 3 functions:
* connect(): It will open a connection to a specific host selecting a specific database too.
* getContent(): It will retrieve the last messages from our shoutbox table in plain text.
* insertMessage(): It will insert the new message in our shoutbox table.
So here you have the three functions:
/************************ FUNCTIONS /************************/ function connect($db, $user, $password){ $link = @mysql_connect($db, $user, $password); if (!$link) die("Could not connect: ".mysql_error()); else{ $db = mysql_select_db(DB); if(!$db) die("Could not select database: ".mysql_error()); else return $link; } } function getContent($link, $num){ $res = @mysql_query("SELECT date, user, message FROM shoutbox ORDER BY date DESC LIMIT ".$num, $link); if(!$res) die("Error: ".mysql_error()); else return $res; } function insertMessage($user, $message){ $query = sprintf("INSERT INTO shoutbox(user, message) VALUES('%s', '%s');", mysql_real_escape_string(strip_tags($user)), mysql_real_escape_string(strip_tags($message))); $res = @mysql_query($query); if(!$res) die("Error: ".mysql_error()); else return $res; }
It's almost finished guys. As we said, we will manage via switch sentence the POST requests from AJAX (from the future shoutbox.js file) so we will make use of the three previous functions to retrieve and insert data:
/****************************** MANAGE REQUESTS /******************************/ if(!$_POST['action']){ //We are redirecting people to our shoutbox page if they try to enter in our shoutbox.php header ("Location: index.html"); } else{ $link = connect(HOST, USER, PASSWORD); switch($_POST['action']){ case "update": $res = getContent($link, 20); while($row = mysql_fetch_array($res)){ $result .= " <li><strong>".$row['user']."</strong><img src="\" alt="\"-\"" />".$row['message']." <span class="\"date\"">".$row['date']."</span></li> "; } echo $result; break; case "insert": echo insertMessage($_POST['nick'], $_POST['message']); break; } mysql_close($link); }
And that's all in the PHP part guys.
Just comment that we are avoiding the direct access to shoutbox.php by checking the post variable action that we send in each request to shoutbox.php from javascript code (from shoutbox.js remember).
Let's go to the final step… the AJAX part!
Step 5: Adding AJAX and some magic with jQuery
So now we have done the layout with the CSS, the shoutbox table in a MySQL database and the PHP script to insert / retrieve data.
We only need to know how to make POST requests from our shoutbox.js javascript file to our soutbox.php PHP script file.
All the following code will be in a javascript file named shoutbox.js and in the $(document).ready of jQuery. First of all we will define some variables to save some references to jQuery selectors:
[code lang="phpl"] //global vars
var inputUser = $("#nick");
var inputMessage = $("#message");
var loading = $("#loading");
var messageList = $(".content > ul");
[/code]
We will need a function to check if all fields are filled before send the data to our database, it will be called checkForm():
//check if all fields are filled function checkForm(){ if(inputUser.attr("value") &amp;&amp; inputMessage.attr("value")) return true; else return false; }
As we said in the Step 1, we will load the messages of our shoutbox table via AJAX from the first instance, so let's create a function to retrieve this data:
function updateShoutbox(){ //just for the fade effect messageList.hide(); loading.fadeIn(); //send the post to shoutbox.php $.ajax({ type: "POST", url: "shoutbox.php", data: "action=update", complete: function(data){ loading.fadeOut(); messageList.html(data.responseText); messageList.fadeIn(2000); } }); }
What's happening here? We are showing the loading animated gif while we are retrieving data from shoutbox table via POST request to our shoutbox.php.
With the data parameter of $.ajax() function we can send post variables (action = update), in this case we are sending $_POST['action'] = "update", so shoutbox.php can manage the specific action in the switch sentence that we have made before.
Finally when the request is completed, we hide the loading animated gif, load the new data in our xHTML layout and show it.
So adding a call to this function, updateShoutbox() in the ready event of jQuery we can load the data in a first instance:
//Load for the first time the shoutbox data updateShoutbox();
Finally we need to manage the submit event to insert user's messages in our shoutbox table and then refresh the content in the shoutbox (with the updateShoutbox() function, you know):
//on submit event $("#form").submit(function(){ if(checkForm()){ var nick = inputUser.attr("value"); var message = inputMessage.attr("value"); //we deactivate submit button while sending $("#send").attr({ disabled:true, value:"Sending..." }); $("#send").blur(); //send the post to shoutbox.php $.ajax({ type: "POST", url: "shoutbox.php", data: "action=insert&nick=" + nick + "&message=" + message, complete: function(data){ messageList.html(data.responseText); updateShoutbox(); //reactivate the send button $("#send").attr({ disabled:false, value:"Shout it!" }); } }); } else alert("Please fill all fields!"); //we prevent the refresh of the page after submitting the form return false; });
Demo: http://www.yensdesign.com/tutorials/shoutbox
Download: http://yensdesign.com/tutorials/shoutbox/shoutbox.zip
Source: http://yensdesign.com/2009/01/create-a-shoutbox-using-php-and-ajax-jquery/
Related Listings:
- Ajax Shout box – Very Simple This script is based on jQuery library and Form plugin.It’s...
- Mini Chat – wTag Ajax Shoutbox A free open source shoutbox script, using Ajax to refresh...
- Ajax Script – Free Rich Text Editor Free Rich Text Editor is same like a WYSIWYG editor...