Quick and easy GetURL class / actionscript 3 urlrequest

Here is a quick basic flash url loader for quickly adding links to buttons and movie clips in Actionscript 3:

// GetURL Class by Rick Nuthman
// 10.4.09
// Usage:
// new GetURL("url", "target");

package com.frigidfish{
   
    import flash.net.*;
   
    public class GetURL{
       
        private var request:URLRequest;
       
        public function GetURL(url:String, target:String = '_self'){
           
            request = new URLRequest(url);         
            navigateToURL(request, target);
           
        }
    }
}

It’s just a bare bones script that works like the old getURL() method from actionscript 2.
It defaults to opening the url in a blank page, but you can change this by modifying the 2nd parameter.

import com.frigidfish.GetURL;

// you can add it right to an event listener for a button or movieclip

yourButton.addEventListener(MouseEvent.CLICK, function(){ new GetURL("your_url.html", "_self")});

// or by itself
new GetURL("your_url.html");

I like using this because it makes the code a lot cleaner and easier to read when you have a bunch of links to deal with in Flash. Enjoy!

Load SWF via Actionscript 3 with this class

Here is a class that you can use to load swf’s into an object that you can display or do whatever you’d like with:

// SWFLoader Class by Rick Nuthman
// 2.10.10
//
// Usage:
/*
var mySWF:Object;
mySWF = SWFLoader.create("urlToSWF.swf", 0,0);
mySWF.dispatcher.addEventListener("ready", displaySwf);
function displaySwf(event:Event){
    addChild(mySWF.swf);
}
*/


package com.frigidfish{

    import flash.display.Sprite;
    import flash.display.Loader;
    import flash.events.Event;
    import flash.net.URLRequest;
    import flash.events.EventDispatcher

    public class SWFLoader{        

        public function SWFLoader() {
        }

        public static function create(url, x=0,y=0):Object {
           
            var loaded:Event                = new Event("ready");
            var dispatcher:EventDispatcher  = new EventDispatcher();
            var swf:Sprite                  = new Sprite  ;
            var mLoader:Loader              = new Loader  ;
            var obj:Object                  = new Object;
           
            obj.swf = swf;
            obj.dispatcher = dispatcher;
           
            swf.x = x;
            swf.y = y;
           
            var mRequest:URLRequest = new URLRequest(url);
            mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,swfLoaded);

            mLoader.load(mRequest);

            function swfLoaded(event:Event) {
                var target = event.currentTarget.content;              
                swf.addChild(target);  
                dispatcher.dispatchEvent(loaded);
            }
           
            return obj;
        }
    }
}

You don’t need to make an instance of the class, just use the static function ‘create’ like so:

var mySWF:Object;
mySWF = SWFLoader.create("urlToSWF.swf", 0,0);
// You can replace 0,0 in the previous line with
// initial x,y coordinates for your swf
mySWF.dispatcher.addEventListener("ready", displaySwf);
function displaySwf(event:Event){
    addChild(mySWF.swf);
}

I have been using this class to load a bunch of swfs into an array of objects.. I built a preloader that says something like “loading foo.swf…” for each swf as they are loading. Then when the “ready” event has fired for all of the swfs I add them all to a container sprite and display them.

flash and php – Send/Receive Variables from Actionscript 3 & PHP

Below is a class that I made that can be used to send a group of variables to a php script on a server and receive the results. I use this all the time when working between flash and php in my projects!

// FlashPHP Class by Rick Nuthman
// 8.28.09
// Constructor receives 2 arguments:
// url:String - The url to the PHP file
// flashVars:Object - An object that contains variables to be sent to the url
//
// The class dispatches 1 event called "ready" once the php transaction is complete.
// listen for this event. Once it's received you can access returned variabled from receievedVars.

package com.frigidfish{

    import flash.net.URLVariables;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.net.URLLoaderDataFormat;
    import flash.net.URLRequestMethod;
    import flash.events.EventDispatcher;
    import flash.events.Event;

    public class FlashPHP extends EventDispatcher {
       
        // Public Properties
        public var receivedVars:URLVariables;      
       
        // Private Properties
        private var url:String;    
        private var flashVars:Object;
        private var request:URLRequest;
       
        private var completeEvent:Event              = new Event("ready");
        private var variables:URLVariables           = new URLVariables();
        private var loader:URLLoader                 = new URLLoader();

        public function FlashPHP(url:String, flashVars:Object) {
           
            this.flashVars                      = flashVars;
            this.url                            = url+"?r="+ new Date().getTime();
           
            parseVariables();
        }

        // Private Methods
        private function parseVariables() {
           
            for (var item in flashVars) {
               
                variables[item] = flashVars[item];             
            }
           
            sendVariables();
        }

        private function sendVariables() {
           
            request                                 = new URLRequest(url);
            request.method                          = URLRequestMethod.POST;
            request.data                            = variables;
           
            loader.dataFormat                       = URLLoaderDataFormat.VARIABLES;           
            loader.addEventListener(Event.COMPLETE, variablesAreLoaded);
            loader.load(request);
        }

        function variablesAreLoaded(event:Event) {
           
            receivedVars                            = new URLVariables(loader.data);
            dispatchEvent(completeEvent);          
        }
    }
}

Here is an example of how to implement it:

import com.frigidfish.FlashPHP;
var score:String = "100";
var playerName:String = "Bobby";
var phpData:*;

var playerObject:Object = new Object();
playerObject.score = score;
playerObject.playerName = playerName;

var flashPHP:FlashPHP = new FlashPHP("http://www.yoursite.com/yourphp.php", playerObject);
flashPHP.addEventListener("ready", processPHPVars);

function processPHPVars(event:Event){
// put the object that php sends back into a var (in this case phpData)

phpData = event.target.receivedVars;
trace(phpData.success);
}

Of course it will be necessary to know what to do with the data on the PHP side… here is a simple script that receives that variables and sends back a simple response var called ‘success’:

<?php
$teamName = $_POST['playerName'];
$score = $_POST['score'];
// Here you would put any processing functions...
//...

$success = "1";
//...
$returnVars = array();
$returnVars['success'] = $success;
$returnString = http_build_query($returnVars);
echo $returnString;
?>

Basically, this script does nothing with the variables that are collected, but as you can see, it just takes what is posted from flash and assigns it to php variables. Lastly, we create a new array to contain any vars that will be sent back to flash. This array is converted into a query string which is translated by FlashPHP into an object containing the variables by key names created in PHP.

I hope this makes sense, it’s actually quite easy to use! Don’t forget to wait for the FlashPHP “ready” event to trigger before attempting to access its receivedvars property. Feel free to ask any questions if anything doesn’t make sense šŸ™‚

Download Example

actionscript 3 preloader freezes at 100% (SOLVED!)

Have you ever embedded an swf into an html docuement and all seemed fine until you started getting calls from customers saying that the preloader is stuck at 100%?

Well I have, and it took me quite some time to figure this out.

If you embedĀ  different wmode, such as wmode=transparent,Ā  Firefox will load the first frame of your swf but then it appears to lock up!

It turns out that theĀ  loaderInfo Event.COMPLETE and PROGRESS are not firing.

Here is my working preloader:

stop();

var preLoaderPercent:Number = 0;

addEventListener(Event.ENTER_FRAME, loadComplete);

function loadComplete(e:Event):void {

if (this.loaderInfo.bytesLoaded == this.loaderInfo.bytesTotal) {

removeEventListener(Event.ENTER_FRAME, loadComplete);
this.loaderInfo.removeEventListener(Event.COMPLETE, loadComplete);
this.loaderInfo.removeEventListener(ProgressEvent.PROGRESS, loadProgress);
gotoAndStop(2);
}
}

this.loaderInfo.addEventListener(Event.COMPLETE, loadComplete);
this.loaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress);

function loadProgress(e:ProgressEvent):void {
preLoaderPercent = e.bytesLoaded / e.bytesTotal;
preloader.percentText.text = Math.ceil(preLoaderPercent * 100) + "%";
}

Basically this is a normal preloader with one addition.. On each frame (line 5) the function loadComplete is called. This function is SUPPOSED to be called when ProgressEvent.PROGRESS (line 19) is fired. Anyway, loadComplete (line 7) checks to see if the number of bytes loaded is the actual size of the file. This is basically a failsafe in the case that ProgressEvent.PROGRESSĀ  fails to fire!

What a weird bug.. Anyway, it works!