Getting Perl and Flex talking via XML

Flex and Flash are very capable tools and its often very trivial to get them talking to all different kinds of back ends. Today we will get Perl talking to Flex via XML and its easier than you might think.

To work through this you will need the following:
1. Flex Builder 3 – a free trial is available
2. Access to a web host that runs Perl, or a Perl distribution hooked to a web server of some sort.

The first thing we’ll do is create a very simple Perl script that will render out some XML:

#!/usr/bin/perl

use strict;
use XML::Writer;

print "Content-type: text/xml\n\n";

my $xml = new XML::Writer();

$xml->startTag("root");
  $xml->startTag("messages");
    $xml->dataElement(msg1=> "Hello World");
    $xml->dataElement(msg2=> "Goodbye World");
    $xml->endTag();
    $xml->endTag();
  $xml->endTag();
$xml->end();

You can hit that page with your browser and hopefully see a result like this:

<root>
	<messages>
		<msg1>Hello World</msg1>
		<msg2>Goodbye World</msg2>
	</messages>
</root>

Lets create a simple Flex application to test this out. Fire up Flex Builder 3 and call the new project “TalkToPerl”.

Creating the project

I modified my MXML page to look like this:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
	<mx:Script>
		<![CDATA[

            private function onResult():void
            {
                txt.htmlText = txt.htmlText + "<br/>Msg1: " + xmlService.lastResult.messages["msg1"];
                txt.htmlText = txt.htmlText + "<br/>Msg2: " + xmlService.lastResult.messages["msg2"];
            }
		]]>
	</mx:Script>

	<mx:HTTPService id="xmlService" result="onResult();" resultFormat="e4x" url="http://YOUR_WEB_HOST_ADDRESS/cgi-bin/perltest.cgi" />

	<mx:Panel width="350" height="280" layout="absolute" horizontalCenter="0" verticalCenter="0" color="#000000" fontSize="12" fontFamily="Verdana">
		<mx:Button x="126.5" y="10" label="Test Me" click="xmlService.send();"/>
		<mx:TextArea x="10" y="42" width="310" height="188" id="txt" verticalScrollPolicy="on"/>
	</mx:Panel>
</mx:Application>

The real trick here is that in the MX:HTTPService tag we added this attribute: resultFormat=”e4x”. E4X is EcmaScript 4 XML. This allows Flex to interpret and parse the data as XML thus making this statement make sense to retrieve the data:

[as]
xmlService.lastResult.messages["msg1"]
[/as]

Run the project and you should hopefully see something like this:

First results

Pretty easy huh? Ok, now lets pass in some parameters to the Perl script from Flex and have Perl send back something based on those parameters. We can do this by adding this code:

	<mx:HTTPService id="xmlService" result="onResult();" method="POST" resultFormat="e4x" url="http://YOUR_WEB_HOST_ADDRESS.com/cgi-bin/perltest.cgi">
		<mx:fault>Alert.show(event.toString(), event.type);</mx:fault>
        <mx:request xmlns="">
            <message>My new message</message>
        </mx:request>
	</mx:HTTPService>

We display an alert if we encounter an error, but otherwise we pass in “message” with the value “My new message” via a POST. We now need to modify the Perl script to have the ability to extract the POST variable(s) and do something with it. In this case I’ll simply place that value into the msg1 section of the XML.

#!/usr/bin/perl

use strict;
use XML::Writer;
use CGI qw(:standard);

print "Content-type: text/xml\n\n";

my $xml = new XML::Writer();

$xml->startTag("root");
  $xml->startTag("messages");
    $xml->dataElement(msg1=> param("message"));
    $xml->dataElement(msg2=> "Goodbye!");
	$xml->endTag();
$xml->endTag();
  $xml->endTag();
$xml->end();

So the final MXML is going to look like this:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
	<mx:Script>
		<![CDATA[
			import mx.controls.Alert;

            private function onResult():void
            {
                txt.htmlText = txt.htmlText + "<br/>Msg1: " + xmlService.lastResult.messages["msg1"];
                txt.htmlText = txt.htmlText + "<br/>Msg2: " + xmlService.lastResult.messages["msg2"];
            }
		]]>
	</mx:Script>

	<mx:HTTPService id="xmlService" result="onResult();" method="POST" resultFormat="e4x" url="http://YOUR_WEB_HOST_ADDRESS.com/cgi-bin/perltest.cgi">
		<mx:fault>Alert.show(event.toString(), event.type);</mx:fault>
        <mx:request xmlns="">
            <message>My new message</message>
        </mx:request>
	</mx:HTTPService>

	<mx:Panel width="350" height="280" layout="absolute" horizontalCenter="0" verticalCenter="0" color="#000000" fontSize="12" fontFamily="Verdana">
		<mx:Button x="126.5" y="10" label="Test Me" click="xmlService.send();"/>
		<mx:TextArea x="10" y="42" width="310" height="188" id="txt" verticalScrollPolicy="on"/>
	</mx:Panel>
</mx:Application>

Run the application and you should see this:

The final result

As you can see passing data to and from Flex to Perl via XML is very easy to do.

2 Responses to “Getting Perl and Flex talking via XML”

  1. [...] Giant Flying Saucer Programming Parlor Tricks « Getting Perl and Flex talking via XML [...]

  2. Mobius says:

    Line 16 in your PERL file is unnecessary. It throws an error. $xml->end(); is sufficient.

    Also, I’ve been trying to get this to work and haven’t had any luck. I’m testing locally. I don’t think it should make a difference since I can run perl scripts locally and I can run flex apps locally. Am I wrong here?

Leave a Reply