Javascript and Flex Communication

11 04 2008

A couple days a go I was writing a quick flex app at work and it became necessary for me to be able communicate between javascript and flex, that is, making javascript calls from flex and making flex calls from javascript. After a bit of research, I found that it is a pretty easy thing to do. To make it easier to see what is going on I’m splitting this up into two separate examples.

Making javascript calls from flex:

<?xml version="1.0" encoding="iso-8859-1"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="300" height="86" layout="absolute"  >
    <mx:Script>
    	<![CDATA[
        	import flash.external.*;
 
    		function buttonClicked():void {
    			ExternalInterface.call("alert", userInputField.text);
    		}
		]]>
    </mx:Script>
 
	<mx:TextInput id="userInputField" x="20" y="28"  width="191"/>
	<mx:Button label="JS Alert" click="buttonClicked()"  x="219" y="28"/>
</mx:Application>

Get FlashPlayer

The above example makes a simple call to the javascript function “alert” and passes the text in the text field as an argument to the alert function. To pass more than one argument simply just add them as additional arguments to the ExternalInterface.call() method. Example: ExternalInterface.call(”myJsFunction”, “arg1″, “arg2″);


Making flex calls from javascript:

<?xml version="1.0" encoding="iso-8859-1"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="300" height="86" layout="absolute" creationComplete="init()" >
    <mx:Script>
    	<![CDATA[
        	import flash.external.*;
 
    		function init():void {
    			ExternalInterface.addCallback("setTextField", setTextField);
    		}
 
    		function setTextField(userInput:String):void {
    			userInputField.text = userInput;
    		}
		]]>
    </mx:Script>
 
	<mx:TextInput id="userInputField" x="20" y="28"  width="191"/>
</mx:Application>
var flexApp;
 
if (navigator.userAgent.indexOf("MSIE") != -1) {
	flexApp = window[flexElementObjectId];
} else {
	flexApp = document[flexElementObjectId];
}
 
flexApp.setTextField("Hello World");

This example invokes a flex function from javascript. As you may have noticed this is relatively simple, all you need to do is add a an external callback within flex and make a call to the DOM object from Javascript.



Upload XML into Flex

10 01 2008

Today I was asked to add some functionality to a flex application I have been developing, that functionality was to give users the option to upload the XML data file, rather than fetch it from the server. I won’t go in to the details of the application, just that it is completely driven on its data, which is provided via XML. After doing some reading I was surprised to learn that it is not possible to upload an XML file without a server side script of some kind. I choose to use PHP because its quick, easy, and simple. So the concept is that the user sends the file through flex to a server side script, that script accepts the file and returns its contents back to flex as XML.

Here is the flex code:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
  layout="absolute" width="275" height="354" 
  creationComplete="init()">
<mx:Script>
<![CDATA[
  import mx.rpc.events.*;
  import flash.events.*;
  import flash.net.FileReference;
  import flash.net.URLRequest;
  import flash.net.FileFilter;
 
  private var myXML:XML;
  private var file:FileReference;
 
  private function init():void {
    file = new FileReference();
 
    // Add Event Listners
    file.addEventListener(Event.SELECT, userSelectedFile);
    file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, serverResponse);
  }
 
  private function browse():void {
    file.browse([new FileFilter("XML", "*.XML;")]);
  }
 
  // Called after the user selects the file to upload
  private function userSelectedFile(event:Event):void {
    file = FileReference(event.target);
    file.upload(new URLRequest("file_upload.php"), "FileData", false);
  }
 
  // Called after flex receives response from PHP
  private function serverResponse(event:DataEvent):void {
    myXML = XML( event.data );
    XML_Box.data = myXML;
  }
]]>
</mx:Script>
<mx:VBox>
</mx:VBox>
  <mx:Button id="Upload" label="Upload" click="browse()" x="200" y="322"/>
  <mx:TextArea id="XML_Box" width="250" height="300" x="12.5" y="10"/>
</mx:Application>

Here is the php code:

<?php
// Set the header information
header ("content-type: text/xml");
 
// Open the uploaded file
$file_handler = fopen($_FILES["FileData"]["tmp_name"], "r");
 
// Display the file contents
while(!feof($file_handler))
{
        echo fgets($file_handler);
}
 
// Close the file
fclose($file_handler);
?>

That’s all there is to it! To try it out just click the upload button and select an XML file to upload. If you don’t have an XML file handy you can use this sample file.
Get FlashPlayer



The power of recursion

5 01 2008

Recursion can be a powerful technique for any programmer, but it’s important to understand its application, when it should be used and when it should not be.The whole idea behind recursion is to have a function or method which calls itself, this has the effect of breaking down the data in sub portions so that it can be handled easier. One of the most common applications for recursion is used injunction with tree data structures. In a tree data structure each node contains data and any number of sub nodes or children which may also contain data and any number of children.Here is a very common example of recursion in which we calculate the Fibonacci Number.

int fibonacci( int n )
{
  if( n == 0 )
    return 0;
  if( n == 1 )
    return 1;
  if( n > 1 )
    return fibonacci(n-1) + fibonacci(n-2);
}

Now you have a very small function, but powerful function that can easily and accurately compute a Fibonacci number. This is just one of the many useful applications of a recursive function. If I have peaked your interest I recommend that you continue reading about recursion, the wikipedia recursion article is a good start.



Hello world!

21 12 2007
<script type="text/javascript">
  alert('Hello World!');
</script>
<?php
  echo "Hello World!";
?>
public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello World!");
  }
}
#include <iostream>
 
int main()
{
  std::cout << "Hello World!" << std::endl;
  return 0;
}

You get the idea.