22 Replies Latest reply on Aug 31, 2007 2:57 AM by williamkusumo

    Multiple HttpService Requests

      Hello everyone! I am new to flex 2 and have encountered a proble with httpservice. Im developing a small content management system which can be used in education. I will be using a php and mysql backend and flex 2 frontend. My problem is I am hoping to use multiple httpservice requests to complete much of my functionality e.g. one httpservice called login would call a login php script to authenticate the user, another httpservie called register called register would be used to register a new user when they click on the register button. Once the user has logged in i would like to use a 3rd httpservice request called loadprofile which would call profile php script which would then search the database a return relevant information. This may seem a silly question to more experienced devlopers but I was wondering if it is possible to make multiple httpservice requests in a single mxml application file? Someone please help me as i have hit a brick wall and this problem is holding up my app which i need to finish in the next few weeks. Thanks!
        • 1. Re: Multiple HttpService Requests
          chris.huston.t10 Level 3
          Yes, you can have multiple HTTPService requests in a single app. When you make a request, you can specify the function to process the result and then deal with the returned data in each of these functions. Avoid binding your results directly in mxml with result.lastResult properties since this will make debugging quite difficult. Here is an example with two requests:

          url=" http://some.server.com/script1.php"
          url=" http://some.server.com/script.2php"

          private function resultFxn1(evt:ResultEvent):void {
          myDataGrid.dataProvider = evt.result;

          private function resultFxn2(evt:ResultEvent):void {
          myComboBox.dataProvider = evt.result;
          myComboBox.labelField = "someField";

          • 2. Multiple HttpService Requests
            Shark_Attack Level 1
            Thanks Vygo for your help as it has set me on the right path. Now i have another question in relation to this code you have so kindly provided. Say i have a button called service1 which calls request 1 and a second button service2 which calls the second service. Is the actual code to envoke these:
            <mx:Button label="Service1" id="Service1Button" click="request1.send()"/>
            <mx:Button label="Service2" id="Service2Button" click="request2.send()"/>

            Also in the resulltFxn2 would it be possible to display the results in a label,textarea,text etc control instead of a datagrid or comobox as in your example. Hope you will so kind as before and help me out again.
            • 3. Re: Multiple HttpService Requests
              chris.huston.t10 Level 3
              Your button syntax looks good for sending the requests. You can assign the results from any request to any control such as labels, textAreas and anything else. Just use the id of the label or textArea and set the result to that id.text or whatever property you need. You just have to make sure that the format returned from your PHP script is properly formatted. I generally use XML since that gives me the most flexibility when working with data. You can access the node values with dot notation such as:


              • 4. Re: Multiple HttpService Requests
                Shark_Attack Level 1
                Thanks again Vygo! I still cant get it to work. All thats appearing in as my text is Object Object. My frelevant lex code is:

                url=" http://localhost/request.php"
                <mx:request xmlns="">

                private function resultUserRequest(evt:ResultEvent):void
                myComboBox.dataProvider = evt.result;
                myComboBox.labelField = evt.result.data.emailaddress;

                The part of the php script which returns the XML is:

                //return a list of all the users
                $Query = "SELECT * from users";
                $Result = mysql_query( $Query );

                $Return = "<users>";

                while ( $User = mysql_fetch_object( $Result ) )
                $Return .= "<user><userid>".$User->userid."</userid><username>".$User->username."</username><emailad dress>".$User->emailaddress."</emailaddress></user>";
                $Return .= "</users>";
                mysql_free_result( $Result );
                print ($Return)

                I dont know what im doing wrong to be honest and am at a dead end. Any advise would be most greatfull.
                • 5. Re: Multiple HttpService Requests
                  ntsiii Level 3
                  Specify resultFormat="e4x" on the http service tag. The default is "object", and you do not want that.

                  Multiple HTTPService instance is ok, but makes it unnecessarily difficult to add more calls later, since you will have to write a new tag, a new handler, etc. I like to use a single HTTPService instance, and a single result handler. In order to have a specific call result go to a specfic location or invoke specific processing, I use the AsyncToken.

                  Look at the code snippets below for an exampl on how to set this up cleanly.


                  Sample code using HTTPService, e4x, handler function to populate a list item.
                  Also shows usage of AsyncToken.

                  The DataGrid tag:
                  <mx:DataGrid id="dg" dataProvider="{_xlcMyListData}" .../>

                  The HTTPService tag:
                  <mx:HTTPService id="service" resultFormat="e4x" result="onResult(event)" fault="..../>

                  Script block declaration:
                  import mx.rpc.Events.ResultEvent;
                  [Bindable]private var _xlcMyListData:XMLListCollection;

                  Invoke send:
                  var oRequest:Object = new Object();
                  oRequest.Arg1 = "value1";
                  var callToken:AsyncToken = service.send(oRequest);
                  token.callId = "myQuery1";

                  Result Handler function:
                  private function onResult(oEvent:ResultEvent):void {
                  var xmlResult:XML = XML(event.result); //converts result Object to XML. can also use "as" operator
                  var xlMyListData:XMLList = xmlResult.myListData; //depends on xml format, is row data
                  _xlcMyListData = new XMLListCollection(xlMyListData); //wrap the XMLList in a collection
                  trace(_xlcMyListData.toXMLString()); //so you can see exactly how to specify dataField or build labelFunction
                  var callToken:AsyncToken = oEvent.token;
                  var sCallId = callToken.callId; //"myQuery1"
                  switch(sCallId) {
                  case "myQuery1":

                  • 6. Re: Multiple HttpService Requests
                    ntsiii Level 3
                    Additional note:
                    Binding to an instance variable instead of directly setting the dataProvider gives you access to the list dat later, in case you want to modify it programatically. You can also bind another component to it without having to modify the result handling code
                    • 7. Multiple HttpService Requests
                      Shark_Attack Level 1
                      Hi Tracy thanks for the help. I have included resultFormat="e4x in my httpservice tag. Now instead of oject object i am getting the xml data returned but i still cant extract the data i want from it. For example my returned xml file looks like:


                      the result of the httpservice is the resultFxn1(event) method. In this method i would like to extract the username field of the xml and populate some text control. I have tried a combobox and and a label but i cant seem to get it to work. The code is:

                      private function resultFxn1(evt:ResultEvent):void {
                      MyLabel.text = evt.result.data.username;
                      myComboBox.dataProvider = evt.result;
                      myComboBox.labelField = "username";

                      I just cant seem to extract the data i want. Anyone know where im going wrong?
                      • 8. Re: Multiple HttpService Requests
                        ntsiii Level 3
                        First, put the labelField on the ComboBox tag. You are assigning it after the dataProvider and this might cause a timing issue. Then:

                        Break this up into steps.
                        In your result handler function do this:
                        var xmlUsers:XML = XML(evt.result);
                        trace(xmlUsers.toXMLString()); //do you see what you expect?
                        var xlUsers:XMLList = xmlUsers.user;
                        trace(xlUsers.length()); // do you see the correct number of users?
                        myComboBox.dataProvider = xlUsers;

                        • 9. Re: Multiple HttpService Requests
                          Shark_Attack Level 1
                          Thanks Tracy I now have myComboBox which is populated with the usernames passed by the xml file which is nearly what i want.
                          Now instead of placing this information in a combobox how would i place the information in a textarea or labe. What i want to do is have a user profile which is loaded when the user logs in i.e a personal page which display a name, address, telephone, email etc which will be displayed in text areas or labels. In other words i want to bind a username passed from php script to a text control in my flex app.

                          Hope that makes sense! My brains are fried now so i might not have made my explaination too clear. Hope you can help me once more as you have been great so far.
                          • 10. Re: Multiple HttpService Requests
                            ntsiii Level 3
                            Ok, so we are on a different part of the app?

                            Declare an instance variable:
                            [Bindable]private var _xmlUser:XML;

                            In your result handler, get a reference to the the user node you want:
                            var xlUsers:XMLList = xmlUsers.user; //gets the first user node in users

                            _xmlUser = xlUsers[0]; //the first user under users if you have different xml, adjust this expression

                            <mx:Text id="txtName" text="{_xmlUser.name}" .../>

                            • 11. Re: Multiple HttpService Requests
                              ntsiii Level 3
                              Ignore the comment on this line:
                              var xlUsers:XMLList = xmlUsers.user;

                              copy/paste error on my part
                              • 12. Re: Multiple HttpService Requests
                                Shark_Attack Level 1
                                Thats brilliant Tracy as it works perfect for me in the sample app i have done up. Hope i can put it into my main app now. Just so im clear on this code could you please explain what is happening in the code above.

                                As far as i can see i declare a XML variable which is bindable:

                                [Bindable]private var _xmlUser:XML;

                                Then in my result handler i convert the object passed to it through the Resultevent to XML and store it in an XML varible:

                                var xmlUsers:XML = XML(evt.result);

                                Then i create another XML variable which is an XML list and populate it with data from xmlUsers variable where the node is equal user. This will store all the data from the xml file tagged user:

                                var xlUsers:XMLList = xmlUsers.user;

                                Then just user an array to store each user.

                                _xmlUser = xlUsers[0];

                                Do I have a basic understand of what is happening? Again thanks for your help as I would never have figured this out on my own.

                                • 13. Re: Multiple HttpService Requests
                                  Shark_Attack Level 1
                                  Hello again Tracy! I have encountered some other problems with my mutilple httpservice requests. I want to insert some data into a mysql database table so i have a httpservice called postBlog which does this.

                                  I pass 4 parameters to the php script through this i.e. title,body,username,keywords. A button called submit is used to call postBlog.send(). I have a result event which simply alerts the user that the blog has been entered successfully. When i click the button after a few seconds the alert message appears. However no data is entered into the database. Worried I then done up a quick app which should do the same thing but the result is the same. No data is entered into the database table although the alert does appear.

                                  The mxml code for this app is:

                                  <?xml version="1.0" encoding="utf-8"?>
                                  <mx:Application xmlns:mx=" http://www.adobe.com/2006/mxml" xmlns="*" layout="absolute">
                                  <mx:HTTPService id="postBlog" url=" http://localhost/postblog.php" result="postBlogSuccess(event)" useProxy="false" method="POST">
                                  <mx:request xmlns="">
                                  <title>{txtBlogTitle.text}</title><body>{txtBlogEntry.text}</body><keywords>{txtBlogKeywo rds.text}</keywords><username>{lblShowUserName.text}</username>
                                  import flash.events.*;
                                  import mx.rpc.events.ResultEvent;
                                  import mx.rpc.http.HTTPService;

                                  private function postBlogSuccess(evt:ResultEvent):void {
                                  mx.controls.Alert.show("Entry posted successfully");

                                  <mx:TextInput x="236" y="94" id="txtBlogTitle" text="test"/>
                                  <mx:TextInput x="236" y="164" id="txtBlogEntry" text="work"/>
                                  <mx:TextInput x="236" y="231" id="txtBlogKeywords" text="please"/>
                                  <mx:Label x="236" y="47" text="Mike" width="145" id="lblShowUserName"/>
                                  <mx:Button x="496" y="318" label="Button" click="postBlog.send()"/>


                                  The corresponding php script is:

                                  define( "DATABASE_SERVER", "localhost" );
                                  define( "DATABASE_USERNAME", "root" );
                                  define( "DATABASE_PASSWORD", "" );
                                  define( "DATABASE_NAME", "blog" );

                                  //connect to the database
                                  $mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD);

                                  mysql_select_db( DATABASE_NAME );

                                  //data passed from flex

                                  $title = mysql_real_escape_string($_POST["title"]);

                                  $body = mysql_real_escape_string ($_POST["body"]);

                                  $keywords = mysql_real_escape_string ($_POST["keywords"]);

                                  $username = mysql_real_escape_string ($_POST["username"]);

                                  //add the user to user table
                                  $Query ="INSERT INTO dbblog (title, body, keywords, username) VALUES ('$title', '$body', '$keywords', '$username')";

                                  $Result = mysql_query( $Query );



                                  I have no idea why this is not working. If i got this working hopefully i would be able to get the multiple httpservice scripts working for my original app. You got any ideas?

                                  • 14. Re: Multiple HttpService Requests
                                    ntsiii Level 3
                                    I don't do PHP, so you are on your own at that end.

                                    i do not advise declarative style code for building the request object:
                                    <mx:request xmlns="">
                                    <title>{txtBlogTitle.text}</title><body>{txtBlogEntry.text}</body><keywords>{txtBlogKeywor ds.text}</keywords><username>{lblShowUserName.text}</username>

                                    You have no way of debugging that. Instead, build the request object in AS code, where you can see what is happening. You can also send hard coded values for debugging purposes. see the "Invoke send" section of my code snippets above.

                                    Do you know for sure that the php page is getting hit? Have you tested the PHP functionality with hard coded data?

                                    Now, generally, for debugging any back end, you can make a page that just "echoes" the request arguments you send. build a little xml string, send that back to flex, and trace it to be sure you are sending the values you expect.

                                    Or can you debug the PHP server code live, and stp through the request when it is sent from Flex?

                                    • 15. Re: Multiple HttpService Requests
                                      Shark_Attack Level 1
                                      Thanks for the advise. I solved the problem with the php. I was using wordpad instead of notepad and that seemed to make some difference. Silly mistake to make really but at least i realised it. When you say build a request in AS code is that what you are doing in the code further up the page as i dont really understand the code you posted.
                                      • 16. Re: Multiple HttpService Requests
                                        ntsiii Level 3
                                        <mx:request xmlns="">
                                        <title>{txtBlogTitle.text}</title><body>{txtBlogEntry.text}</body><keywords>{txtBlogKeywor ds.text}</keywords><username>{lblShowUserName.text}</username>

                                        is exactly the same as:
                                        var oRequest:Object = new Object();
                                        oRequest.title = txtBlogTitle.text;
                                        oRequest.body = txtBlogEntry.text;
                                        • 17. Re: Multiple HttpService Requests
                                          Shark_Attack Level 1
                                          And how would i pass these value to the httpservice. Would i be right in thinking its:

                                          <mx:request xmlns="">
                                          • 18. Re: Multiple HttpService Requests
                                            ntsiii Level 3
                                            No, do it as in my snippets above:
                                            var callToken:AsyncToken = service.send(oRequest);

                                            That AS code completely replaces the declarative mxml.

                                            You can skip the AsyncToken if you wish.
                                            • 19. Re: Multiple HttpService Requests
                                              Shark_Attack Level 1
                                              Ah i see now! So if i understand correctly I can take out the httpservice completely and replace it with theses snippets? If that is the case where do i tell it to find my php script?
                                              • 20. Re: Multiple HttpService Requests
                                                ntsiii Level 3
                                                Please read all the snippets in that post.
                                                • 21. Re: Multiple HttpService Requests
                                                  Shark_Attack Level 1
                                                  Ah yes! I have read it properly now. Il give it a try. Anyway thanks for your help Tracy all along. I would have been lost without it. Cheers!
                                                  • 22. Re: Multiple HttpService Requests
                                                    I am having a problem with HTTPService too.

                                                    I am calling a webservice that does something and return HTTP status
                                                    (either success or fail) that's it, no data whatsoever is returned. I
                                                    need to do something when I got the response back but for some reason,
                                                    ResultEvent.RESULT is not firing if there is no data being returned by
                                                    the webservice. Is this how it's supposed to behave? Is there another event I can listen to that'll do this?

                                                    Appreciate the help! Thanks!