Using XML in Flex - Tutorial Part 4 - WebService

Flex provides an ActionScript 3.0 class named WebService and a MXML component named WebService. My references for this tutorial are the Adobe Flex 2 Language Reference, Programming ActionScript 3.0, and the Flex 2 Developer's Guide.

The WebService class and component can be used to access SOAP-based web services. For more information on SOAP-based web services see: http://www.w3schools.com/soap/default.asp.

WebService Class

Let's examine the ActionScript 3.0 WebService class first and provide an example of how to use it. The WebService class exposes several properties and methods. One of the more important properties is wsdl, which is the location of the Web Service Description Language (WSDL) document for the web service. The WSDL document details the services provided by the web service, what inputs are required to use the service, and what outputs the service returns. A detailed description of WSDL is here: http://www.w3.org/TR/wsdl.

My example for this tutorial uses the USZip WebService provided by www.webservicex.net

To use the WebService class you will need this information:

  1. WSDL - for example http://www.webservicex.net/uszip.asmx?wsdl
  2. Method Name - for example GetInfoByCity
  3. Method Parameters - for example USCity
  4. NameSpace (if you want results formatted in e4x XML) - for example http://www.webserviceX.NET (see page 1150 in Flex 2.0 Developer's Guide)

If you examine the WSDL and the SOAP envelope returned you can find the information needed above. The USZip webservice has four methods we can use. In my example I use the GetInfoByCity method. You provide this method the name of a US city and it returns an XML document with the city, state, zip, area code, and time zone. If you examine the complete results returned, you will see that the response specifies an XML namespace of http://www.webserviceX.NET. To properly use the results formatted in e4x XML, you will need to create a namespace object and use it in your Flex app (see page 1150 in the Flex 2.0 Developer's Guide).

After you've created the WebService object, you specify the values for its properties, such as WSDL and resultFormat (e4x). You also specify which functions will handle the result and fault events by using your object name.the webservice method name.addEventListener(...). For example:

WS.GetInfoByCity.addEventListener("result", resultHandler);

The above code specifies that a function named resultHandler will handle the result event for method GetInfoByCity.

One of the event handlers you specify is for the load event. The load event is triggered when the WebService has completed loading the WSDL. Inside the function you specified as handling the load event is where you can call the WebService method. You pass any arguments to the WebService's methods inside the parenthesis:

//call the WebService method GetInfoByCity
WS.GetInfoByCity(city.selectedLabel);

In the above, I'm sending to the WebService method the user's selection in the city combo box.

In the resultHandler function I refer to the XML returned by the webservice method using the dot notation I discussed in tutorial 1.

WS.GetInfoByCity.lastResult is the XML document returned

WS.GetInfoByCity.lastResult.GetInfoByCityResult.NewDataSet.Table[0].ZIP gets the value for the ZIP node that is a child of the first Table element that is a child of the NewDataSet element, that is a child of the GetInfoByCityResult element.

To view the example click here. You can right click on the example to view the source code.

mx:WebService MXML Tag

Instead of the ActionScript 3.0 WebService class you can use the WebService MXML tag. When you use the mx:WebService tag you specify the WSDL and the id value (used to refer to the component later). Inside the mx:WebService tag you use an mx:operation tag to identify the webservice method you want to use and the resultFormat for the data returned by the method. Inside the mx:operation tag you use an mx:request tag to specify the values for the method's parameters. The elements inside the mx:request tag should be named to match the parameter names specified by the webservice method.

To make the call to the webservice method, you use the id value.the method name.send(). For example:

WS.GetInfoByCity.send() (where WS is the id value for the mx:WebService component)

Once the results are returned by the webservice you can bind them to various MXML components. Again you can use the dot notation to get the value of a specific element. You can also use the XML returned to populate a DataGrid.

See the mx:WebService example and right click on it to view the source.

Please post any suggestions for improving this tutorial or questions about areas that I've not properly covered.

Related Blog Entries

Comments
Very useful. The

WS.addEventListener("load", loadHandler);

was key for me; I'd missed this in the Flex docs.
# Posted By David | 10/25/06 9:15 PM
This example is great. The Flex Studio help was just too convoluted and short on examples. Thanks!

One thing I would add in an example is something that I am using for my project....how to send the URL of a web service, using flashvars, into the Flex project. This way, the service is not hard-coded in the project. I couldn't really get this working right using MXML, so I switched to defining the web service in ActionScript.

Basically just
private var myWebServiceURL:String;

and then in InitApp()
myWebServiceURL = Application.application.parameters.webServiceURL;

And finally in the UseWebService() method
MyService.wsdl = myWebServiceURL + "WSDL";
# Posted By Pete | 11/17/06 12:31 PM
Pete:

Good idea. I'll try that next.
# Posted By Bruce | 11/17/06 2:37 PM
I was troubled about wsdl.
But, this article solved it.
Thank you.
# Posted By Tohru | 12/21/06 6:49 PM
This is a great sample app, thanks for providing. It helped me overcome a problem with resolving the complex result back from the webservicex GetInfoByZIP service.
# Posted By Michael Brophy | 6/8/07 1:41 AM
Hi!

I'm a newbie within Flash..I'm currently working with Flash CS3...

I have some questions:

Can i use the code with Flash CS3 a well?
What alternative exists to e4x?

I have a asp.net 2.0 website...which is going to communicate/pass a variable to the action script code(eg. by java script)...which then is going to call a webservice...but how do i call the webservice method: action script code file --> (call) method in the mxml file which then call the real webservice...? how does that looks like?

Please be kind - it is my first flash app! :)

Cheers
Pablo
# Posted By Pablo | 7/17/07 4:21 PM
Pablo - I've not used CS3 so I cannot comment on it. The alternative to e4x is to use the old ActionScript 2 XML syntax.

See the area in my tutorial where I call a webservice in ActionScript.
# Posted By Bruce | 7/19/07 6:34 PM
Hi again!

I have looked at your example...made my own dot net web service, which is very simple...the method is called HelloWorld and is just returning a string (it does not take any in parameters)...and it is working very wel!! :)

This is how my returned XML looks like:

<HelloWorldResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" target="_blank">http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.123.dk/" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<HelloWorldResult>Pablo has problems!</HelloWorldResult>
</HelloWorldResponse>

My question to you is:

How do I get/fetch the text "Pablo has problems!" from the XML??
I have tried for so many hours now and it should be VERY simple!

The DOC says: webservice.method.lastResult.Property;

Which gives:

WS.HelloWorld.lastResult.HelloWorldResult;

I really hope that you can help me on this one, i'm so close this time ;)

Best,
Pablo
# Posted By Pablo | 7/23/07 5:13 PM
Pablo - since your response includes a namespace declaration (xmlns="http://www.123.dk) you will need to declare that namespace in order to use E4X's dot notation. See the tutorial above.
# Posted By Bruce | 7/24/07 7:25 AM
i want to write the webservice in the actionscript,and use the request object to send the operation's parameters, the request is in the xml structure.and my code like this, but i find these is some mistake in the request:
var ws:WebService = new WebService();
ws.wsdl = "http://weblogs.macromedia.com/mxna/webservices/mxn...
ws.useProxy = false;
ws.getMostPopularPosts.addEventListener("result", doResultHandler);
ws.getMostPopularPosts.request =<request><daysBack>30</daysBack><limit>5</limit></request>*/;
ws.addEventListener("fault",faultHandler);
ws.getMostPopularPosts();   
ws.loadWSDL();
ws.getMostPopularPosts.send();
# Posted By jessica | 8/6/07 8:45 PM
Jessica - I've not used the request object property. However, the order of your code might be part of the problem. Study the source code for the ActionScript example in the above tutorial. You need to wait until the loadWSDL() method returns before requesting the webService method.
# Posted By Bruce | 8/8/07 12:23 PM
I have to pass an xml with multiple attribute to SOAP.
<soap12:body>
<method>
<someParameter attrube0="int" atribute1="string" attibutex="Boolean"/>
<otherParameter>String</otherParameter>
</method>
</soap12:body>

I can not pass someParameter as object or xml then it throwes a HTTP request error. If pass it as xmlString or String. then I get a new error back from the server.

"Error #1069: Property attrube0 not found on String and there is no default value."

I hope that there is a sollution to pass xml with attributes
# Posted By Adam Koncz | 8/14/07 9:08 AM
Hi,
As above. When I try to send an Object with SOAP I get a (Error #2032: Stream Error) error. The crossdomain.xml is ok. And i can use the webservice when I only pass single values like int or string. Is it some kind of serialization error? Is there a way to tell the SOAP how to serialize?
Cheers,
Adam
# Posted By Adam | 8/16/07 5:11 AM
Adam - I've not had to pass an Object to a SOAP web service. Try searching through the Yahoo FlexCoder's group.
# Posted By Bruce | 8/16/07 1:06 PM
hye..awesome article ..helped me alot but i have a problem....i made my webservice in dot net and it returns this when i call

myChart.getData.lastResult.toXMLString()

<getDataResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns="http://tempuri.org/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" target="_blank">http://www.w3.org/2001/XMLSchema-instance">
<getDataResult>
<int>45</int>
<int>65</int>
<int>2</int>
</getDataResult>
</getDataResponse>

Can you pls tell me how can i bind the
<int>45</int>
<int>65</int>
<int>2</int>

to a pie chart or data Grid Single col..i have tried doing it the following way but it brings emty grid and empty chart

For data Grid
=====================================================
<mx:DataGrid dataProvider="{myChart.getData.lastResult.getDataResult}">
<mx:columns>
<mx:DataGridColumn dataField="int" headerText="Random Nos"/>
</mx:columns>
</mx:DataGrid>

For Pie Chart
====================================================
<mx:PieChart id="chart" showDataTips="true" dataProvider="{myChart.getData.lastResult.getDataResult}" >

<mx:series>
<mx:PieSeries labelPosition="callout" field="int"></mx:PieSeries>
</mx:series>
</mx:PieChart>

Pls help me on this
# Posted By helloworld | 9/4/07 12:30 AM
i have also added the namepace

private namespace webXNameSpace = "http://tempuri.org/";
use namespace webXNameSpace;

but the above code i pasted still brings empty grid and pie chart
i have been tryin this for days now pls help me where am going wrong
# Posted By helloworld | 9/4/07 12:41 AM
HelloWorld - Try extracting from the XML returned just the int node values and using them to create an XMLListCollection and use that as the data provider.

Search my blog for XMLListCollection for an example.
# Posted By Bruce Phillips | 9/4/07 2:05 PM
i am new to flex started 2 days back :(..pls tell me why is it that we cannot directly bind the result of the service to the controls...i have tried the webservice X and it binds correctly...why is this service not binding correctly ??...

can you tell me how do i extract int nodes
# Posted By helloworld | 9/4/07 10:57 PM
helloworld - I'm sorry but I don't have time right now to trouble shoot your code. I recommend you study the Flex developer's guide (see adobe.com) for how to use XML with Flex. There are several examples in the guide of using XML as the data provider for various Flex controls.
# Posted By Bruce | 9/5/07 11:55 AM
helloworld - in the function that process the XML after it is returned by the webservice try using some trace statements to get values of individual nodes:

trace ( mychart.getDataLastResutlt.getDataResult.int[0] ) for example.

Then run your app in debug mode and see if any value is pulled out of the xml and displayed in the console.
# Posted By Bruce | 9/5/07 2:06 PM
helloworld - it may be the node name (int) is causing a problem. Try this statement

trace (mychart.getDataLastResutlt.getDataResult.child("int") );

You can use the child() method to get the all the child nodes named "int"

Also if you want to send me the webservice you're using, I'll test it when I can.
# Posted By Bruce | 9/6/07 10:14 AM
what is difference between the result format E4x and XML
# Posted By helloworld | 9/7/07 10:30 PM
# Posted By Bruce | 9/11/07 9:23 AM
Your code is really helpful. I am trying to do the same way, but using my own webservice.

The method is my webservice returns countries results in xml format and country name is CDATA type.

I am able to load countries xml data in TextArea control but not in the DataGrid control.

Does CDATA type has to do anything with datagrid not showing data ? I tried displaying just country id but that didn't solve the problem. Any help is appreciated .
# Posted By siri | 9/18/07 11:12 AM
Siri: I've not used a webservice that returns CDATA as the data provider for the grid. I've used it for a list without a problem though. I believe the element that contains the CDATA should work just fine in the grid. I would first check that the XML being returned is properly formatted by running the XML through a validation service (see w3c.org).
# Posted By Bruce | 9/18/07 12:48 PM
Thanks Bruce.

I solved the issue. The issue is with resultFormat="e4x" attribute in the operaton tag. Once i removed it, the datagrid gets loaded but not the TextArea. I am trying to solve this, so it will display in TextArea and Datagrid just like in your example.
# Posted By Siri | 9/19/07 8:28 AM
hi ,
your tutorial is really helpful.But i want to know how to send an xmlstring from flex application to a webservice which accepts it as input parameter and do some processing.
thanx. waiting for ur reply
# Posted By krishna mohan | 9/20/07 12:21 AM
Krishna - My example code shows how to send parameter values to the webservice. Perhaps you can store your XMLString in a variable and use that variable as the parameter to the webservice (similar to how I send the US City in my example).
# Posted By Bruce | 9/20/07 9:46 AM
Thanx bruce. when sending xml data as input i had a problem.iam using mxml tag to invoke a webservice.the webservice input is xmlstring.i have taken the string variable and assigned the xmldata to it and passing that string as input inside <request > tag of <operation>.The problem is < symbol in xml it is not taking as input .when i try to use &lt; its working fine.why it is happeninig so .how can i input the xml data to webservice.
# Posted By krishnamohan | 9/21/07 2:32 AM
My web service is working fine with flex. but some time s it takes more than 5 min to get the data (beacuase of the query delay).

i used tmeout varible to close web service with in 2 min. but it does not release channels. total browser struked for ever.

i am unable to do new request unless i close and reopen the browser.
# Posted By pradeep | 10/2/07 1:17 PM
Hello Bruce,

I am having problem when I use the .swf file in my .aspx file. When I am use your example (webServiceExample.html's .swf file in .aspx file and refer in <InvalidTag> tag, it works fine. But with my .swf file, it loads .swf file and once user make selections and click "OK" button, it just hangs up, and i don't get any error message. I am guessing there is a security issue. Any help is appreciated.

Thanks,
Siri
# Posted By Siri | 10/11/07 1:40 PM
It is not InvalidTag, it is Object tag

Siri
# Posted By siri | 10/11/07 1:42 PM
BlogCFC was created by Raymond Camden. This blog is running version 5.1.004.