Archive for June 2nd, 2008

Flex up front, LAMP down back, XML in the middle

Monday, June 2nd, 2008

We all know LAMP. It’s the free and open source basis for many a web server. L for Linux (the OS), A for Apache (the web server software), M for MySql (the database) and P for PHP (the coding language).


Usually.. or, at least, in the past.. php was used to return html to the browser. Based on some database query, you echoed a name or a number with some tags and such. Your presentation layer (the html) was therefore intermingled with your code. There are lots of ways to make this nice.. but.. it’s not needed anymore, now Flex is here.


A Flex front end basically asks a server somewhere for some data, it comes back, and it gets displayed. This sounds nice, but Flex takes a little bit of convincing to get it to work. Here’s how I did it..


This first ‘bit’ is the HTTPService (from the Flex code). It controls sending the request to the server. Note the url. This is where your php file is. This php file must not return HTML. It must return XML. The xml should look something like this:

<?xml version="1.0" encoding="utf-8" ?>
<thingThree />
<thingOne>hello world</thingOne>
<thingThree />

To get the HTTPService to ‘fire’, just call myhttpservice.send();.
Then the function defined as the ‘result’ takes over:

private var result2:XML;
private function myhttpservice_result(event:ResultEvent):void {
result2 = XML(event.result);

Presuming you were using a DataGrid to display the data, you would set dataProvider="{result2.rows.row}"
And then refer directly to the fields for your columns dataField="thingOne"


And just to prove it works…
The working example
A zip file with the source code


Note also that you will probably want to send extra data with your initial request like a search term. To do this, add a few lines before your send() command:

var parameters:* = {
"parameterOne": "555",
"parameterTwo": "something"
myhttpservice.request = parameters;

They can then be read in your PHP as normal, with a reference like $_REQUEST['parameterOne'].