Passing parameters to an HTTPService

by Peter deHaan on October 29, 2007

in HTTPService, StringValidator, ValidationResultEvent

The followig example shows how you can pass parameters to an HTTPService by passing an Object in the HTTPService’s send() method. The remote ColdFusion script is a simple “hello world” type script which accepts a single parameter, “name”, and returns a single parameter, “welcomeMessage”.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/10/29/passing-parameters-to-an-httpservice/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;
            import mx.events.ValidationResultEvent;
            import mx.utils.StringUtil;

            private function submit_click(evt:MouseEvent):void {
                var result:ValidationResultEvent = stringValidator.validate();
                var params:Object = {};

                lbl.text = "";

                switch (result.type) {
                    case ValidationResultEvent.INVALID:
                        Alert.show(result.message, result.type);
                        break;
                    case ValidationResultEvent.VALID:
                        params["name"] = StringUtil.trim(firstName.text);
                        httpServ.send(params);
                        break;
                }
            }
        ]]>
    </mx:Script>

    <mx:StringValidator id="stringValidator"
            source="{firstName}"
            property="text"
            minLength="2"
            maxLength="{firstName.maxChars}" />

    <mx:HTTPService id="httpServ">
        <mx:resultFormat>flashvars</mx:resultFormat>
        <mx:url>http://www.flash-mx.com/mm/greeting.cfm</mx:url>
        <mx:result>lbl.text = httpServ.lastResult.welcomeMessage;</mx:result>
        <mx:fault>Alert.show(event.toString(), event.type);</mx:fault>
    </mx:HTTPService>

    <mx:ApplicationControlBar dock="true">
        <mx:Form>
            <mx:FormItem label="Name:" required="true"
                    direction="horizontal">
                <mx:TextInput id="firstName"
                    maxChars="20" />
                <mx:Button label="Submit"
                        click="submit_click(event);" />
            </mx:FormItem>
        </mx:Form>
    </mx:ApplicationControlBar>

    <mx:Label id="lbl" fontSize="32" />

</mx:Application>

View source is enabled in the following example.

By popular request, here is the ColdFusion source code as well.

http://www.flash-mx.com/mm/greeting.cfm

<cfsilent>
<cfsetting enablecfoutputonly="Yes">
<cfif IsDefined("URL.name")><cfset Form.Name = URL.name /></cfif>
<cfif NOT IsDefined("Form.name") OR Len(Trim(Form.Name)) EQ 0>
    <cfset Form.Name = "[Mysterious Stranger]" />
</cfif>
</cfsilent><cfcontent reset="true" /><cfoutput>welcomeMessage=#UrlEncodedFormat("Welcome, "&Form.name)#</cfoutput>
<cfsetting enablecfoutputonly="No">

{ 20 comments… read them below or add one }

1 Pankaj Tiwari March 14, 2008 at 4:40 am

Hi,
nice tutorial. Can you please the same exaple using java as remote script to handle the request. Also do upload the script code as well. This will give clear picture

Thank’s

Reply

2 Mas May 28, 2008 at 2:24 am

Hi! Do you have the .cfm file? Is it possible if i take a look? Because i’m having problem how to write it.

Reply

3 Liceven May 30, 2008 at 8:26 am

Hi, I have a question about <mx:url>http://www.flash-mx.com/mm/greeting.cfm</mx:url>
I want to replace this URL with my local url like:http://localhost:8080/baidusongs/greeting.cfm
and the file content of greeting.cfm is:
welcomeMessage=Welcome%2C%20%5BMysterious%20Stranger%5D
but it doesn’t work; error message is as bellow:

[FaultEvent fault=[RPC Fault faultString="Security error accessing url" faultCode="Channel.Security.Error" faultDetail="Destination: DefaultHTTP"] messageId=”35B47C6E-A306-19F6-5CB9-3A6DB07123C8″ type=”fault” bubbles=false cancelable=true eventPhase=2]
thanks for your time!

Reply

4 Liceven May 30, 2008 at 8:29 am

yes, maybe i have the same problem with Mas.
Thanks…

Reply

5 peterd May 30, 2008 at 8:35 am

Mas,

I updated the entry above, hope that helps.

Peter

Reply

6 peterd May 30, 2008 at 8:37 am

Liceven,

You may be getting a security error if your SWF/HTML is using the file:/// protocol and your webservice/CFM is running on http://.
I’d start by copying the contents of the /bin-debug/ or /bin-release/ folders into the same directory as the .CFM file and view the sample over HTTP.

Peter

Reply

7 Liceven May 30, 2008 at 11:07 pm

Hello,peterd,
I copy all the files in folder /bin-debug/ to the same directory as the .cfm. And view the swf over http. It don’t pop up the error dialog this time, but it doesn’t display welcome information either.
And i viewed the greetinng.cfm using IE browser. I found the return contents are different.
http://www.flash-mx.com/mm/greeting.cfm—&gt;welcomeMessage=Welcome%2C%20%5BMysterious%20Stranger%5D
whiel http://localhost:8080/flexweb/greeting.cfm returns welcomeMessage=#UrlEncodedFormat(“Welcome, “&Form.name)#
why? i have little knowledge about coldfusion. so, thanks very much.

Reply

8 peterd May 30, 2008 at 11:39 pm

Liceven,

Looks like your ColdFusion server isn’t parsing the .CFM templates for some reason. Which version of ColdFusion did you install?

Peter

Reply

9 Liceven May 31, 2008 at 1:42 am

ColdFusion MX 7
Maybe there is something wrong with the configuration.
Thanks very much Peterd.

Reply

10 Waqas July 23, 2008 at 8:26 pm

I am having problem using HTTPService, Can u please help me for the problem mentioned on the link below?

http://board.flashkit.com/board/showthread.php?t=772909

Reply

11 Halfway there... August 27, 2008 at 11:49 am

It’s broken, I get a fault “channel security error”.

Reply

12 peterd August 27, 2008 at 11:59 am

Yeah, looks like http://www.flash-mx.com is down.

Reply

13 sandhya September 29, 2008 at 3:17 am

Hi ,

Can u specify an example how to write httpservice in actionscript

Reply

14 Gustavo November 3, 2008 at 8:14 pm

Hello, nice tutorial!

but why flashvars????

Tks!

Reply

15 Naveen November 24, 2008 at 10:16 am

Hi,

Your site has been really helpful to learn Flex, appreciate your time. I’m learning flex and I’m stuck here, not sure how to debug this issue. I do not get any error, but the DB is not getting inserted with the value. Any help on fixing the issue, will be great.

Below are the key codes:

submit button code:

addAnnouncement function code:

private function addAnnouncement( evt:Event) :void{
var selArr:Array = [];
var oRequest:Object = new Object();
var idx:int;
var len:int = userRequest. lastResult. partners. partner.length;
for (idx=0; idx

INSERT INTO tblAnnouncement
(strTitle, strContent, dtmOpenDate,
dtmCloseDate, dtmAssignmentDueDat e )
VALUES
(,
,
,
,

)

i’m stuck here..not sure, where to look for the bug..i do not see
any error..any help is really appreciated.

-NB

Reply

16 Tomas January 24, 2009 at 9:24 pm

BTW, I had a problem in which I tried to pass an XML object as a parameter using Flex 3 and it wouldn’t appear at the server. What I did was to create another object with its only key-value pair containing the string representation of the XML object.

Thanks for the blog.

Reply

17 jayanthi March 18, 2009 at 2:39 am
18 Peter deHaan March 18, 2009 at 6:40 pm

jayanthi,

I’ve never tried that. It may depend on the server configuration. I imagine sending X number of parameters with the same name will either overwrite the previous parameter’s value, or else if you’re lucky the server may convert the duplicate parameters into an array/list (so the server may convert the name to “testName1,testName2,testName2″.

You’d have to experiment with your specific server and see what the behavior is.

Peter

Reply

19 Jhon July 29, 2009 at 10:48 am

I have a problem with the latin character, I can´t insert into data base mysql the values á,í,,,,,,,ñ,etc. Can you help me.

Reply

20 Jonas October 8, 2009 at 2:06 pm

I typed “Ação”
The return was: AÃ…

How to troubleshoot problems with Latin characters?

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: