Dynamically loading XML files using the HTTPService tag

by Peter deHaan on March 29, 2008

in HTTPService, TileList, XMLListCollection

In previous examples, “Creating a simple image gallery with the Flex TileList control” and “Creating a simple image gallery with the Flex HorizontalList control”, we saw how you could create a simple image gallery using the TileList and HorizontalList controls.

The following example shows how you can load XML files using the HTTPService tag so that you can dynamically load different galleries.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/03/29/dynamically-loading-xml-files-using-the-httpservice-tag/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.rpc.events.ResultEvent;
            import mx.rpc.events.FaultEvent;
            import mx.controls.Alert;

            private var alert:Alert;

            private function loadGallery(src:String):void {
                httpService.url = src;
                httpService.send();
            }

            private function httpService_fault(evt:FaultEvent):void {
                var title:String = evt.type + " (" + evt.fault.faultCode + ")";
                var text:String = evt.fault.faultString;
                alert = Alert.show(text, title);
                xmlListColl.removeAll();
            }

            private function httpService_result(evt:ResultEvent):void {
                var xmlList:XMLList = XML(evt.result).images.image;
                xmlListColl = new XMLListCollection(xmlList);
            }
        ]]>
    </mx:Script>

    <mx:XMLListCollection id="xmlListColl" />

    <mx:HTTPService id="httpService"
            resultFormat="e4x"
            fault="httpService_fault(event);"
            result="httpService_result(event)" />

    <mx:ApplicationControlBar dock="true">
        <mx:Button label="gallery 1"
                click="loadGallery('gallery1.xml');" />
        <mx:Button label="gallery 2"
                click="loadGallery('gallery2.xml');" />

        <mx:Button label="gallery 404"
                click="loadGallery('gallery404.xml');" />
    </mx:ApplicationControlBar>

    <mx:TileList id="tileList"
            dataProvider="{xmlListColl}"
            itemRenderer="TileListItemRenderer"
            columnCount="3"
            columnWidth="150"
            rowCount="2"
            rowHeight="100" />

</mx:Application>

TileListItemRenderer.mxml

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/03/29/dynamically-loading-xml-files-using-the-httpservice-tag/ -->
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml">

    <mx:Image source="{data.@src}"
            horizontalCenter="0"
            verticalCenter="0" />

    <mx:Label text="{data.@lbl}"
            fontWeight="bold"
            horizontalCenter="0"
            bottom="0" />

</mx:Canvas>

View source is enabled in the following example.

{ 18 comments… read them below or add one }

1 Benny April 4, 2008 at 12:37 am

Thanks for all your examples, they are very helpful! By chance, do you know to write to an xml-file from within Flex using PHP? Or maybe have a link to share? Would be nice use above code to read from xml and somehow be able to update thet xml-file dynamically also.

Thanks again, very appreciated!
/Benny

Reply

2 Michael April 30, 2008 at 1:47 pm

I know how to make an XML file using PHP, mail me and i will help you out.

BTW nice article. Helps a lot !! :)

Reply

3 e11world July 29, 2009 at 3:23 pm

Hi Michael,
I’m just wondering if you or anyone here knows how to load multiple/dynamic xml files into the fla from php/asp
Instead of doing the same old xml.load(‘myfile.xml’);, I want to load different xml files per user from a database for example. I have the php/asp code but not sure how to get flash to work with that.
I guess I need some sort of parameter like xml.load(url:String) .
I haven’t done AS2 in a while so it feels like it’s all new to me. Thanks for the help in advance.

Reply

4 Cedric June 7, 2008 at 3:52 am

How do I reload the data of the XMLListCollection?

<mx:HTTPService id="xml_httpservice_q1" url="q1.php?randomnumber=(randomnumber)" resultFormat="e4x"/>
<mx:XMLListCollection id="xml_result_q1" source="{xml_httpservice_q1.lastResult.resultaat}"/>

and on creationComplete: xml_httpservice_q1.send();

I get the XML data, no problem there.

when I perform xml_httpservice_q1.send(); a second time (I want to reload the data from the q1.php since it has changed), I receive the following error:

warning: unable to bind to property ‘resultaat’ on class ‘XML’ (class is not an IEventDispatcher)

Reply

5 sameer July 10, 2008 at 11:37 pm

I’m following up with this example but When I click the Button to load gallery. I get the Following error. I’m using Flex Builder 3.

Error: Unable to load ”.
at mx.controls::SWFLoader/loadContent()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\controls\SWFLoader.as:1368]
at mx.controls::SWFLoader/load()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\controls\SWFLoader.as:1211]
at mx.controls::SWFLoader/commitProperties()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\controls\SWFLoader.as:1015]
at mx.core::UIComponent/validateProperties()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\core\UIComponent.as:5670]
at mx.managers::LayoutManager/validateClient()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\managers\LayoutManager.as:791]
at mx.controls.listClasses::TileBase/measureWidthOfItems()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\controls\listClasses\TileBase.as:1860]
at mx.controls.listClasses::TileBase/commitProperties()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\controls\listClasses\TileBase.as:2327]
at mx.core::UIComponent/validateProperties()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\core\UIComponent.as:5670]
at mx.managers::LayoutManager/validateProperties()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\managers\LayoutManager.as:519]
at mx.managers::LayoutManager/doPhasedInstantiation()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\managers\LayoutManager.as:669]
at Function/http://adobe.com/AS3/2006/builtin::apply()
at mx.core::UIComponent/callLaterDispatcher2()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\core\UIComponent.as:8460]
at mx.core::UIComponent/callLaterDispatcher()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\core\UIComponent.as:8403]

Reply

6 Miguel Torres July 18, 2008 at 12:40 pm

Hi Peterd, first of all i want to thank you for all your great tutorials and example files, you are a life saver!!!
I have modified this example of yours becouse i only want to load 1 gallery XML file.
But i am experiencing much errors.
I would like the TileList to load the “gallery1.xml”file automatic without the end-user clicking on the button.

I really tried everything i thought would fix this, but no success.

Thanks again, have a nice day.

————-
Miguel Torres

Reply

7 Miguel Torres July 18, 2008 at 12:44 pm

This is the code i am working on rite now, actually its your code, modified by me ;)
Thanks

Reply

8 Miguel Torres July 18, 2008 at 12:47 pm
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
		layout="vertical"
		verticalAlign="middle"
		backgroundColor="white">

	<mx:Script>
		<![CDATA[
			import mx.rpc.events.ResultEvent;
			import mx.rpc.events.FaultEvent;
			import mx.controls.Alert;
			import mx.events.ListEvent;
			import mx.events.ItemClickEvent;
			import flash.net.URLRequest;

			private var alert:Alert;

			private function loadGallery(src:String):void {
				httpService.url = src;
				httpService.send();
			}

			private function httpService_fault(evt:FaultEvent):void {
				var title:String = evt.type + " (" + evt.fault.faultCode + ")";
				var text:String = evt.fault.faultString;
				alert = Alert.show(text, title);
				xmlListColl.removeAll();
			}

			private function httpService_result(evt:ResultEvent):void {
				var xmlList:XMLList = XML(evt.result).images.image;
				xmlListColl = new XMLListCollection(xmlList);
			}

			private function tileList_itemClick(evt:ListEvent):void {
            var link:URLRequest = new URLRequest(evt.itemRenderer.data.@url);
				navigateToURL(link);
			}
		]]>
	</mx:Script>

	<mx:XMLListCollection id="xmlListColl" />

	<mx:Button label="gallery 1" click="loadGallery('gallery1.xml');" />

	<mx:HTTPService id="httpService"
			resultFormat="e4x"
			fault="httpService_fault(event);"
			result="httpService_result(event)" />

	<mx:TileList id="tileList"
			dataProvider="{xmlListColl}"
			itemRenderer="TileListItemRenderer"
			columnCount="3"
			columnWidth="150"
			rowCount="2"
			rowHeight="100"
			itemClick="tileList_itemClick(event);"/>

</mx:Application>

Reply

9 Miguel Torres July 18, 2008 at 12:48 pm
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
		layout="vertical"
		verticalAlign="middle"
		backgroundColor="white">

	<mx:Script>
		<![CDATA[
			import mx.rpc.events.ResultEvent;
			import mx.rpc.events.FaultEvent;
			import mx.controls.Alert;
			import mx.events.ListEvent;
			import mx.events.ItemClickEvent;
			import flash.net.URLRequest;

			private var alert:Alert;

			private function loadGallery(src:String):void {
				httpService.url = src;
				httpService.send();
			}

			private function httpService_fault(evt:FaultEvent):void {
				var title:String = evt.type + " (" + evt.fault.faultCode + ")";
				var text:String = evt.fault.faultString;
				alert = Alert.show(text, title);
				xmlListColl.removeAll();
			}

			private function httpService_result(evt:ResultEvent):void {
				var xmlList:XMLList = XML(evt.result).images.image;
				xmlListColl = new XMLListCollection(xmlList);
			}

			private function tileList_itemClick(evt:ListEvent):void {
            var link:URLRequest = new URLRequest(evt.itemRenderer.data.@url);
				navigateToURL(link);
			}
		]]>
	</mx:Script>

	<mx:XMLListCollection id="xmlListColl" />

	<mx:Button label="gallery 1" click="loadGallery('gallery1.xml');" />

	<mx:HTTPService id="httpService"
			resultFormat="e4x"
			fault="httpService_fault(event);"
			result="httpService_result(event)" />

	<mx:TileList id="tileList"
			dataProvider="{xmlListColl}"
			itemRenderer="TileListItemRenderer"
			columnCount="3"
			columnWidth="150"
			rowCount="2"
			rowHeight="100"
			itemClick="tileList_itemClick(event);"/>

</mx:Application>

Reply

10 Miguel Torres July 20, 2008 at 9:49 am

Hi,

I have found a method to automaticly load de XML file without pressing the button. I thought post it in here for anybody who has the same problem as I had.

I just added a creationComplete in the mx:Aplicaiton tag passing the “loadGallery (‘gallery1.xml’);”

This might NOT be best practice, but for now its the only way I know to make it work.

Again, thanks a lot for your great tuto´s and examples.

Reply

11 Joshua July 22, 2008 at 9:33 am

With the AdvancedDataGrid, if you bind an XMLListCollection to the dataProvider it works perfectly. However, if you bind the same XMLListCollection to the GroupCollection source so that you can do grouping and summary rows, it won’t seem to accept it and instead throws an error.

To solve this, I switched my HTTPService from the format of “e4x” to “object” and it worked perfectly. Basically, you just need a more basic data source it seems like an array or object?

Thought I’d note this since it took me a couple hours to figure out (yes, I’m new :)

.:Joshua

Reply

12 Craig M September 10, 2008 at 12:40 pm

Thanks for this! This was exactly what I needed to get my app working.

Reply

13 michelle November 20, 2008 at 7:21 pm

hi,

i’ve tried inputting the code in Flex 3 but it has an error saying HTTP Request Error when i click on the gallery 1 link button. Any reason why?

I would like the thumbnails to appear when the page is loaded, how do i go about doing that?

Reply

14 Mark February 22, 2009 at 6:54 pm

<?php
// Name: makegallery.php (PHP 5.x)
// Who: Created by mallsop.com 10/18/2008
// What: Dynamically get all photos in a folder and make an xml file.
// Then name your gallery folder ‘mygallery’. Place this file there.
// Licence: GPL.
// How: Call this file instead of your xml file in your flex code.
function scanDirectory($dirid, $dirname) {

$return = “<”.”?xml version=\”1.0\” encoding=\”UTF-8\”?”.”>\n”;
$return .= “<galleries>\n”;
$return .= “<gallery id=\”$dirname\”>\n”;
$return .= “<description>$dirname</description>\n”;

while (($file = readdir($dirid)) != false) { // loop
if (($file != “.”) && ($file != “..”)) { // isa file
// get the file extension
$break = explode(“.”, $file);
$file_ext = $break[1];
$file_ext_lowercase = strtolower($file_ext);
if (($file_ext_lowercase == “gif”) OR ($file_ext_lowercase == “jpg”) OR ($file_ext_lowercase == “png”)) { // isa picture
// $filename = $dirname.$file;
$file_size = filesize($file);
// sizes
if ($file_size >= 1073741824) {
$file_size = round($file_size / 1073741824 * 100) / 100 . ” gb”;
}
elseif ($file_size >= 1048576) {
$file_size = round($file_size / 1048576 * 100) / 100 . ” mb”;
}
elseif ($file_size >= 1024) {
$file_size = round($file_size / 1024 * 100) / 100 . ” kb”;
}
else {
$file_size = $file_size . ” bytes”;
}

$return .= “<photo>\n”;
$return .= “<name>$file</name>\n”;
$return .= “<description>$file_size</description>\n”;
$return .= “<source>$dirname/$file</source>\n”;
$return .= “</photo>\n”;
} // end isa picture
} // end isa file to check
} // end loop

$return .= “</gallery>\n”;
$return .= “</galleries>\n”;

return ($return);
} //end function

// run script
$path = getcwd();
$dirname = basename($path); // “.”;
$dirid = opendir(“.”);
$results = scanDirectory($dirid, $dirname);
closedir($dirid);
// display the xml file on screen
echo $results;
// end of script
?>

Reply

15 Venkat March 18, 2009 at 11:58 am

Hi,

In my Flex applicatio im handling the Http Response that will be in a form of XML.
I use to get the AttributeCollection from the event
like

var tempProjectData:ArrayCollection = event.result.Data.Project;

It was working and i use this as a dataprovider for many components.

But after my development i noticed that when i have only one record, then the event.result.Data is not an ArrayCollection. So im getting error.

my xml looks like this

suma

if i had another entry like

suma
suma

then there is no problem.
Please let me know how to see whether event.result.data is Object or ArrayColllection and assign to Object ot ArrayCollection respectively

Reply

16 FUNimations May 5, 2009 at 8:08 am

I got the same problem as Venkat

Reply

17 Larry Kramer May 13, 2009 at 2:44 pm

Thanks for another great example. Could you shed some light on how to make the images display in a pop-up window like inthe horizontal and the vertical tile-list examples?

Keep up the great work,
Larry

Reply

18 Ali Kaba June 16, 2009 at 1:29 pm

Can you a tutorial on connecting a gallery to picasa or any web albums applications? your examples are really great.

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: