Posted on January 23rd, 2006
25945 views
Welcome back to an exclusive Flash 8 tutorial.
Everybody knows this cool Shoutboxes that you see all around the place, but have you ever seen a Flash Shoutbox? Probably yes, have you ever searched for a tutorial about it? Probably yes, did you found one (working)? NO! So here you have one that will for work for sure!! Let's begin with the requirements:
1. mySQL database ------------------------------------------------------- We are using 3 fields for our shoutbox (id, name, message) you can expand this to whatever you want, I'm just showing you the basic principles of it. So let's create a table in our database, for that you can use this sqlscript and enter it your mysql console or you can create it by your own. DROP TABLE IF EXISTS `shoutbox`; CREATE TABLE IF NOT EXISTS `shoutbox` ( `id` int(111) NOT NULL auto_increment, `name` text NOT NULL, `message` longtext NOT NULL, PRIMARY KEY (`id`) ) TYPE=MyISAM PACK_KEYS=0 AUTO_INCREMENT=0 ; .sql script good we now have our database up & running, maybe you want to enter some values inside so we can test it more easily. mySQL part is done, we don't need to touch it anymore. 2. PHP & XML ------------------------------------------------------- Foreword: I'm not explaining every step on the PHP scripts, I will show you the code that I've use, and explain some small stuff which is needed to clear up AND.. this is just the very basic PHP that I've used, no security, no performance improvement. "if someone knows how to do it better and would like to improove it, you're welcome to send me a PM or email shout.php <?php header(\"Content-type: text/xml\"); $host = \"localhost\"; $user = \"username\"; $pass = \"password\"; $database = \"databasename\"; $linkID = mysql_connect($host,$user,$pass) or die (\"Could not connect to host.\"); mysql_select_db($database,$linkID) or die (\"Could not find database.\"); $query = \"SELECT * from shoutbox ORDER BY id DESC\"; $resultID = mysql_query($query,$linkID) or die (\"Data not found\"); $xml_output = \"<?xml version =\\"1.0\\"?>n\"; $xml_output = \"<shouts>n\"; for ($x = 0; $x < mysql_num_rows($resultID); $x++){ $row = mysql_fetch_assoc($resultID); $xml_output .= \"t<shout>n\"; $xml_output .= \"tt<name>\" . $row['name'] . \"</name>n\"; $xml_output .= \"tt<message>\" . $row['message'] . \"</message>n\"; $xml_output .= \"t</shout>n\"; } $xml_output.= \"</shouts>\"; echo $xml_output; ?> Short explanation:
I would like to mention that with this script, we are generating an xml file which we later will import to flash, for the moment you just need to know that with this script, we are creating an extract of the mysql table XML wellformatted! next we need to have a php which will post the data that is being received from flash into the sql database. post.php <? mysql_connect(\"localhost\",\"username\",\"pass\"); mysql_select_db(\"db_name\"); $submit = $_POST['submit']; $name = $_POST['name']; $message = $_POST['message']; if($submit){ $result=MYSQL_QUERY(\"INSERT INTO shoutbox (id,name,message)\".\"VALUES ('NULL','$name','$message')\"); } else { } ?> I think this is pretty straight forward
Let's get to the more interesting part :) 3. FLASH ------------------------------------------------------- Layout / graphics Let us create a basic layout in Flash, I've just drawn a few basic shapes to define the field positions as you may see here, you can also import your own design from photoshop or your favourite graphics application. As next we need to create some buttons, we need a total of 4 buttons
Create your send button and convert it from a shape to a movieclip by pressing F8, I've named it "send_btn". place it in the stage and give it an instance name of send_btn this is very important so that we are able to call the button from the main timeline. Do the same for the reset button, and give it an instancename of reset_btn. Last but not least we need to create the 2 arrow movieclips for the scrolling textbox. you don't need to give them an instancename since we are as an exception inserting the needed code inside the movieclip. Before we move on to Actionscript, we need to create 2 input textfields and 2 dynamic text field, place them on a new layer on top of the layout that we made before, maybe it's good to lock the layout layer so that we don't mess up the layout. In this screenshot you can see the dotted lines of the text fields: For displaying the shouts we are creating a big dynamic textfield with the instancename shouts multiline and render text as html need to be selected, disable the selectable option. Now we need to create 2 input text fields so our users can send us their shouts, place them again on the same layer where the previous textfield has been created and give them an instancename of name_txt and message_txt give each them also a variable name, I've used name and message for this purpose. And as last we create a small dynamic textfield somewhere where you can see it, and give it an instance name of status_txt. The layout part of this tutorial is now finished, let's move on to the programming part, personally most interesting part. ActionScript First of all create a new layer and name it actions to keep things clean and tidy ;) Press F9 to open the actions panel and resize it, you will write a lot of stuff in there now :) We need to build a function which "parses" our xml that is being created from the PHP script into readable flash arrays. Here I show you the complete function use that I've used for it, explanation below. function loadXML(loaded){ if(loaded){ var myXML = xmlData.firstChild.childNodes; _global.nameA=[]; _global.messageA=[]; for(i=0;i < myXML.length;i++){ _global.nameA[i] = this.firstChild.childNodes[i].childNodes[0].firstChild.nodeValue; _global.messageA[i] = this.firstChild.childNodes[i].firstChild.nextSibling.nextSibling.firstChild.nodeValue; shouts.htmlText += \"<b>\" + nameA[i] + \"</b>\"; shouts.htmlText += messageA[i] + \"<br><br>\"; } } } function loadXML(loaded){ if(loaded){ Here we create a new function called loadXML and we pass the parameter loaded with it. on the second line we ask flash if the function has been loaded sucessfuly. var myXML = xmlData.firstChild.childNodes; Defining a variable called myXML, so we can check how many entries are in the xml file. _global.nameA=[]; _global.messageA=[]; Creating 2 global arrays that will hold the entries of the XML for(i=0;i < myXML.length;i++){ _global.nameA[i] = this.firstChild.childNodes[i].childNodes[0].firstChild.nodeValue; _global.messageA[i] = this.firstChild.childNodes[i].firstChild.nextSibling.nextSibling.firstChild.nodeValue; shouts.htmlText += \"<b>\" + nameA[i] + \"</b>\"; shouts.htmlText += messageA[i] + \"<br><br>\"; } } } firstLine: creating a for loop which will be looped as many times as "nodes / entries" in the XML. secondLine: feed the array with the nodeValue of the childNode (in our configuration the name node) thirdLine: feed the array with the nodeValue of the childNode (in our configuration the message node) fourthLine: defining that our text that we are sending to our shouts textfield is HTMLtext, using the += operator you can be sure that every entry will be appended instead of replaced. fithLine: sames as fourth. Now you see why the textfield needs to be rendered as HTML.. we need to format the entries in a nice readabled way, something that our PHP can't do, so let's flash do the work. okay, the function is done, now we need to call our "XML" so it can be readed into Flash, for that we need this piece of code: xmlData = new XML(); // create new XML Object xmlData.ignoreWhite = true; // Ignore whitespaces xmlData.onLoad = loadXML; //as soon as the xml object has been loaded run the function loadXML xmlData.load(\"http://yourdomain.com/shoutbox/shout.php\");//load the \"xml\" file ;) You can already press CTRL+ENTER and do a testrun to see if you get any entries from your mysql table. If you followed all my instructions correctly and entered some data in your table via the phpmyadmin console. Now we need to create the button functionality, let's first start with the send button, but before we write any code, let us check what needs to be done when you press the send button: 1. Check if the input fields have been filled 2. Grab the input 3. send it to our php file. This 3 tasks can be executed with this script send_btn.onPress = function(){ if (name_txt.text eq \"\" or message_txt.text eq \"\"){ // check for empty fields status_txt.text = \"error\"; // if fields empty, shoot an error message }else{ var container:LoadVars = new LoadVars(); //Container holding variables container.name = name_txt.text; //assigning the value of the textfield to a variable inside container container.message = message_txt.text; //assigning the value of the textfield to a variable inside container container.submit = true; //tell the container that the send button has been pressed container.send(\"http://www.yourdomain.com/shoutbox/post.php\",\"_self\", \"POST\");//send the data to php _root.status_txt.text = \"shout sent\";// shoot a success message } } The reason why you need to give an instance name to your input textfields is just because of value assignment to the container, maybe this could be done in some other way, but I think this is suitable for our needs Next we need to assign our reset button a functionality to clear the input fields, here the easy script for that: reset_btn.onPress = reset_btn.onRelease = function(){ name_txt.text = \"\"; //clear textfield name_txt message_txt.text = \"\"; //clear textfield message_txt } Pretty easy no? :o) Now we need to tell our dynamic textbox that it can be scrollable, this is done with this small snippet which will ask for the value of the variable up or down and accordingly scroll it by one line you can also change it to a higher number. The onEnterFrame function is very useful, as you maybe noticed, we have one single frame in our whole movie don't think that flash will just stop after it loaded all the code we've written, it will play frame 1 25 times per second, so as long as the playhead is "entering" frame 1 this function is being called. onEnterFrame = function(){ if (_root.up) { _root.shouts.scroll += 1; } else if (_root.down) { _root.shouts.scroll -= 1; } } From where does flash get the variable _root.up / _root.down ? That's the last bit of code that we need to write, then we're done with the whole shoutbox, so don't go away, we are really done soon. Select your up arrow and press F9 to open your actionspanel and paste this code: on (rollOver) { _root.down = true; } on (press, release, releaseOutside, rollOut, dragOut) { _root.down = false; } Now select your down arrow, press F9 and paste this bit of actionscript: on (rollOver) { _root.up = true; } on (press, release, releaseOutside, rollOut, dragOut) { _root.up = false; } That's it we're done, in the next page you can see the complete code as also download or view a working version :) Complete Flash Code: Layer: Actions Frame:1 function loadXML(loaded){ if(loaded){ var myXML = xmlData.firstChild.childNodes; _global.nameA=[]; _global.messageA=[]; for(i=0;i < myXML.length;i++){ _global.nameA[i] = this.firstChild.childNodes[i].childNodes[0].firstChild.nodeValue; _global.messageA[i] = this.firstChild.childNodes[i].firstChild.nextSibling.nextSibling.firstChild.nodeValue; shouts.htmlText += \"<b>\" + nameA[i] + \"</b>\"; shouts.htmlText += messageA[i] + \"<br><br>\"; } } } xmlData = new XML(); xmlData.ignoreWhite = true; xmlData.onLoad = loadXML; xmlData.load(\"http://www.yourdomain.com/shoutbox/shout.php\"); onEnterFrame = function(){ if (_root.up) { shouts.scroll += 1; } else if (_root.down) { shouts.scroll -= 1; } } send_btn.onPress = function(){ if (name_txt.text eq \"\" or message_txt.text eq \"\"){ status_txt.text = \"error\"; }else{ var container:LoadVars = new LoadVars(); container.name = name_txt.text; container.message = message_txt.text; container.submit = true; container.send(\"http://www.yourdomain.com/shoutbox/post.php\",\"_self\", \"POST\"); status_txt.text = \"shout sent\"; } } reset_btn.onPress = reset_btn.onRelease = function(){ name_txt.text = \"\"; message_txt.text = \"\"; } Movieclip:Up Arrow Frame:1 on (rollOver) { _root.down = true; } on (press, release, releaseOutside, rollOut, dragOut) { _root.down = false; } Movieclip:Down Arrow Frame:1 on (rollOver) { _root.up = true; } on (press, release, releaseOutside, rollOut, dragOut) { _root.up = false; } Summary: The nice thing about working with movieclip symbols instead of button symbols, is that you don't need to care about targetin, everything is located in the main timeline and the actionscript resides (in most cases) in only one single frame, which is very good, if you need to change stuff a few months later. ;) IMPORTANT UPDATE: thanks to Hooch.. I've just noticed that Flash has a problem with loading "cached" content on IE, resulting in a small bug with the shoutbox. To be sure that flash is picking up the newest data from the php, you need to add + replace a few lines: here the updated lines of code Line 1 - cache= random(1000000); Line 19 - xmlData.load("http://www.yourdomain.com/shout/shout.php?cache=" + cache); Line 29 - container.send("http://www.yourdomain.com/shout/post.php?cache="+ cache,"_self", "POST"); Flash will now send a random number to the php which will not affect your display, but it will force IE to "reload" a new PHP ;) - Download the .zip package, including all needed files [HERE] - View a Live Example of the shoutbox [HERE] |