Hello. I have a new blog.

I've moved this blog to the following URL Kerkness.ca. Thank you for visiting, please update your bookmarks.

Thursday, October 16, 2008

Get PHP dynamic variables inside Flex

Let's say that before you load your flex application you want to pass some dynamic variables from PHP for it to act upon. This can be done pretty easily by slipping the values into PHP's  $_GET array and using Flex's ExternalInterface class to get access to them from inside the Flex app.

Here is an example Flex application which pulls values from the URL Query String.

<mx:Application creationcomplete="init()" layout="absolute" xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
private function init():void
{
  var qstr:String = ExternalInterface.call("window.location.search.substring", 1) as String;
  var qarr:Array = qstr.split('&');

  var pairs:Array;
  for( var i:Number = 0 ; i < qarr.length; i++ ){
     pairs = String( qarr[i] ).split('=');
     if( pairs[0] == 'myName' ){
           myName = pairs[1] as String;
     }
  }
}
]]>
</mx:Script>
<mx:Label text="{myName}" />
</mx:Application>

After you build the application and and Flex Builder has generated the .html file that displays your Flex app  you can rename the file .php and then add the following to the top of the file.

<?php $_GET['myName'] = 'Hi I am Kerk'; ?>

Now if you upload your SWF file and PHP file to a server that is running PHP and you open it in your browser you'll  see your value from PHP displayed in your Flex app.

I don't know if that is a clear explanation or not,  or if this is the best way to pass dynamic variables at load time into your flex application but it works for me.  Comments or alternative solutions welcome.

1 comment:

  1. You could also pass in values, through the query string & retreive the data using Application.application.parameters...

    Might not be the most secure though..
    I like your solution! :)
    cheers

    ReplyDelete

Thank you for the comments.