Monday, April 06, 2009

AS3 & Flex : Querying the PHP Server

I had to foray into the work Flex over the last week. Quite a newbie into this part of programming world, it was an interesting change to say the least.

As always, my blog entries are reflection of what I found interesting and thought would be useful to me later on for reference.

So here is how we query a external datasource like PHP Server for a query in Flex.

First and most important control you need to declare for the purpose is the HTTPService control.


<mx:httpservice id="serv" url="../Server/Login.PHP" method="POST" result="resultHandler(event)">
</mx:httpservice>


If you notice, we have given the URL of PHP page to which we would be posting our queries.Also mentioned is a "resultHandler" method which would be handling the events succeeding arrival of reply from the Server.

So how do you make the query in first place ? As you would have guessed, we would be making use of the HTTPService.

var params:Object = {};
params["ACTION"]="LOGIN";
params["PARAM_USERNAME"]="anu";
params["PARAM_PASSWORD"]="anu1";
serv.send(params);

In the above code, I have send the request to server using the serv.Send() method. I am also attaching the Parameters that I need through the method.

Now with that done, the query to PHP server is send out. The PHP page would process the query and send us back the result. In my case the result would be in a XML Format.

As mentioned earlier, the resultHandler method would be fired once the application receives result from the PHP Server.

private function resultHandler(event:ResultEvent):void
{
}

The event parameter in the method would contain the required result you have been waiting for.

Now that doesn’t look too different from coding in C#. Doesn’t it ?