Flex – extra unbound custom parameters in a webservice

One of the greatest parts of Flex is the ease of integration to other servers. As a client side technology, Flex is clearly designed to embrace communication between itself and external servers and not make the programmer jump through hoops to get there. To that end it has the component mx:HTTPService, they can literally be defined in the XML components of your MXML document. That is seriously trivial, close to as easy as writing a tag in an HTML document. Forget worrying about establishing connections, sending data and processing the data returned. Typically, the values sent by the web service are tied to components in the document, e.g. say we have a webservice which sends the value of a textbox called myTextBox to the url http://myserver.com/myurl:

<mx:Script>
    <![CDATA[

        import mx.controls.Alert;
        import mx.rpc.events.ResultEvent;

        private function handleReturn(event:ResultEvent):void
        {
            Alert.show("returned from the webservice");
        }

        private function send():void
        {
            myWebServiceName.send();
        }

    ]]>
</mx:Script>

<mx:HTTPService
    id="myWebServiceName"
    url="http://myserver.com/myurl"
    contentType="application/xml"
    resultFormat="e4x"
    method="POST"
    result="handleReturn(event)">
    <mx:request>
        <sentdata>
            <text>{myTextBox.text}</text>
        </sentdata>
    </mx:request>
</mx:HTTPService>

<mx:TextInput id="myTextBox" />

Here the method send() will invoke the webservice with the up to date textbox data, parse the returned data as XML and call the callback method handleReturn. Great. But what if we want to attach data which is not so easily bindable, say the property of an object defined in your actionscript. Then we just need to set it on the webservice before calling .send(). For example say you had an global ActionScript object user with a public property called id which you needed to send with the request as user_id:

private function send():void
{
    myWebService.sentdata.user_id = user.id;
    myWebServiceName.send();
}

Note that sentdata is just the name of the top level XML node I include all the sent data under, it could be anything of your choosing. Because of the slight slackness of object structure in Flex and Actionscript, you can define the dynamic XML structure on the fly with myWebService.MYTOPNODE.MYNODE = DATA where MYTOPNODE, MYNODE and DATA are all what you need. Good stuff.

Leave a Reply

Your email address will not be published. Required fields are marked *