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

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..

<mx:HTTPService
id="myhttpservice"
url="http://www.thinkquick.com.au/example_xml.php"
resultFormat="e4x"
result="myhttpservice_result(event)"
/>

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" ?>
<response>
<rows>
<row>
<thingOne>something</thingOne>
<thingTwo>1234</thingTwo>
<thingThree />
</row>
<row>
<thingOne>hello world</thingOne>
<thingTwo>999999</thingTwo>
<thingThree />
</row>
</rows>
</response>

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

[Bindable]
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;
myhttpservice.send();

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

Leave a Reply