Sending XML content from Flash

The XML class provides two methods for sending information from Flash: send and sendAndLoad . Both methods work in a similar way by sending the content to an external page for processing. The difference is that the sendAndLoad method also receives a response from the server-side page. Before you send the data out of Flash, you need to set the content type to text/xml . Youll see this next .

Using the send method

The send method sends XML content from Flash to a server-side page. If you are testing the Flash file in a web browser, the method uses POST to send the data, while GET is used from within Flash. This means that you might need to be careful about how you test any files using the send method of the XML class.

The send method has two parameters. The first is the URL of the page that will process the XML content. As this is normally a page written in ColdFusion, PHP, ASP.NET, or some other server-side language, youll need to include the full path through the web server, http://localhost/FOE/page.aspx. If you forget this, the server-side page wont be able to process the updates.

The second parameter is optional and specifies the type of browser window to use to display the response from the server. You can use the HTML target values of _blank , _self , _parent , or _top . If you leave out the parameter, its the same as using a value of _self .

Heres an example of the send method. Notice that the second line sets the contentType property to text/xml .

 var myXML:XML = new XML("XML String"); myXML.contentType = "text/xml"; myXML.send("fullpathtopage.aspx", "_blank"); 

Ive included a working example next, taken from the resource files sendXML.fla and sendXML.html. You can test the Flash movie if you have a web server with the .NET Framework installed. However, before you test the movie, youll need to copy the showXML.aspx file to a directory named FOE in your web server. You dont need to place the Flash and HTML files in the FOE folder for the example to work correctly.

If youd rather work with PHP, you can use the resource files showXML.php and sendXMLPHP.fla . Youll need a web server capable of parsing PHP.

Youll also need to test the resource file sendXML.html through a web browser, rather than through Flash itself. If you test the file within Flash, youll get an error message.

 var XMLString:String; XMLString =  "<login>"; XMLString += "<name>Sas</name>"; XMLString += "<pass>1234</pass>"; XMLString += "<browser>IE</browser>"; XMLString += "<os>PC</os>"; XMLString += "</login>"; var myXML:XML = new XML(XMLString); myXML.xmlDecl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; myXML.contentType = "text/xml"; myXML.send("http://localhost/FOE/showXML.aspx", "_blank"); 

The code creates an XML string and adds it to the myXML object. It adds an XML declaration and sets the content type to text/xml . Finally, it sends the document tree to the page showXML.aspx in the FOE folder in the web server. I had to use the full path to the showXML.aspx file. Figure 4-45 shows the results displayed in a web browser.

image from book
Figure 4-45: A web browser displaying XML sent from Flash

I used an ASP.NET file written in VB to process content from Flash. If you open the resource file showXML.aspx , youll see this content:

 <%@ Page Language="VB" validaterequest="false" ContentType="text/xml" %> <%@ import Namespace="System" %> <%@ import Namespace="System.IO" %> <%@ import Namespace="System.XML" %> <script runat="server">   sub Page_Load(Source As Object, E As EventArgs)     Dim xmlDocument As XmlDocument = New XmlDocument()     Dim sr as StreamReader = new StreamReader(Request.InputStream)     xmlDocument.Load(sr)     response.write (xmlDocument.outerXML)   end sub </script> 

The file sets the content type to text/xml and imports the relevant namespaces. When the page loads, a StreamReader takes the content from Flash and writes it to a new XMLDocument . This is not a physical document. The outerXML of the XMLDocument displays in the browser window. Note that this file doesnt include any error handling.

You could write similar code in any server-side language. Ive chosen ASP.NET because thats the only server-side language I write. As mentioned earlier, a PHP version of this example is available with your resource files.

I dont often use the send method to send XML data from Flash. I prefer to use the sendAndLoad method because it allows me to receive a response from the server-side page. This is useful for locating server-side errors as they can be sent back to Flash and displayed in the application.

Using the sendAndLoad method

The sendAndLoad method works in a similar way to the send method except that it receives a response from the server-side page. Therefore, this method requires two XML objects: one to send the content and one to receive the response. The sendAndLoad method uses POST to send its XML content.

The sendAndLoad method has two parameters: the server-side page for processing the XML content and the name of the XML object that will receive the response. An event handler function for the receiving XML object processes the reply from the server.

The steps to use the sendAndLoad method are as follows :

  1. Create two XML objects, one to send and one to receive. You may already have created the sending object when you first loaded the XML document.

  2. If necessary, assign the XML document tree to the sending XML object. You wont need to do this if you are using an existing XML object.

  3. Set the content type of the sending object to text/xml .

  4. Set the onLoad handler for the receiving XML object.

  5. Call the sendAndLoad method, using the full path to the server-side file and specifying the receiving XML object.

  6. Create the onLoad function to deal with the response in the receiving XML object.

Ive shown some sample code here:

 var myXML:XML = new XML("<login>sas</login>"); var receiveXML:XML = new XML(); receiveXML.onLoad = replyFunction; myXML.contentType = "text/xml"; myXML.sendAndLoad("fullpathtopage.aspx", receiveXML); 

You can see an example of the sendAndLoad method in the resource file sendAndLoadXML.fla . Ive also listed the code here. This time, you can test the file from within Flash. Youll just need to make sure that youre running a web server with the .NET Framework installed. Youll need to copy the server-side file replyXML.aspx to the FOE directory within the web server. Again, if youd prefer, you can use the resource files sendAndLoadXMLPHP.fla and replyXML.php .

The following example sends the XML document tree to replyXML.aspx , which saves the updated content in a physical XML file:

 var XMLString:String; XMLString =  "<login>"; XMLString += "<name>Sas</name>"; XMLString += "<pass>1234</pass>"; XMLString += "<browser>IE</browser>"; XMLString += "<os>PC</os>"; XMLString += "</login>"; var myXML:XML = new XML(XMLString); var replyXML:XML = new XML(); replyXML.onLoad = showResponse; myXML.xmlDecl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; myXML.contentType = "text/xml"; myXML.sendAndLoad("http://localhost/FOE/replyXML.aspx", replyXML); function showResponse(success:Boolean):Void {   if (success) {     trace (this);   }   else {     trace ("Error receiving response");   } } 

The replyXML.aspx page reads the XML content and saves it to a file called login.xml . The XML file is stored in the same location as the replyXML.aspx pagethe FOE directory. Note that the physical file login.xml can only be created if you have permission to write to the FOE directory.

The server-side page also creates a message to send back to Flash. Flash receives it in the replyXML object. When Flash successfully receives a reply, the showResponse function displays it in an Output window. You can see the result in Figure 4-46. If you test the file, youll see a new login.xml file created in the FOE directory of the web server.

image from book
Figure 4-46: Displaying the server-side XML reply in Flash

The VB code that follows shows the contents of the server-side page in a web browser:

 <%@ Page Language="VB" validateRequest="false" ContentType="text/xml"%> <%@ import Namespace="System" %> <%@ import Namespace="System.IO" %> <%@ import Namespace="System.XML" %> <script runat="server">   sub Page_Load(Source As Object, E As EventArgs)     Dim xmlDocument As XmlDocument = New XmlDocument()     Dim xmlResponse AS XMLDocument = New XmlDocument()     Dim strReader as StringReader     Dim strXML as String     Dim sr as StreamReader = new StreamReader(Request.InputStream)     Try       xmlDocument.Load(sr)       xmlDocument.Save(Server.Mappath("login.xml"))       strXML = "The login.xml file has been saved."     Catch ex as exception       strXML = ex.toString     End Try     strReader = new StringReader("<message>" & strXML & "</message>")     xmlResponse.Load(strReader)     response.write (xmlResponse.OuterXML)   end sub </script> 

The page sets its type as text/xml and imports the relevant namespaces. It creates two new XMLDocuments , one to read the contents from Flash and the other to return XML content back to Flash. The page uses a StreamReader to access the content from Flash and load it into an XMLDocument . The Save method writes the content to the file login.xml .

A StringReader composes the return XML string. The second XMLDocument loads the StringReader and writes the outerXML to the browser window. If you know a different server-side language, you could write your own file to achieve the same functionality.

A different approach would be to send only the changed content from Flash. The server-side page would have to figure out what had changed and update the XML existing document. I think its simpler to send the entire document tree from Flash and overwrite the existing XML document each time. It means you can create a simpler server-side file to handle the updating.

Adding custom HTTP headers

The addRequestHeader method of the XML class allows you to create custom HTTP headers when you send XML content from Flash. You might need to do this if your Flash application is working within an environment that requires custom headers, for example, a commercial intranet portal. You can also use the addRequestHeader method to change some of the existing headers.

To add a custom HTTP header, you need to specify the header name and a value. Note that string header values in the second parameter will need to use single quotes.

 myXML.addRequestHeader("headerName", "'headerValue'"); 

You cant change the following standard HTTP headers with the addRequestHeader method:

  • Accept-Ranges

  • Age

  • Allow

  • Allowed

  • Connection

  • Content-Length

  • Content-Location

  • Content-Range

  • ETag

  • Host

  • Last-Modified

  • Locations

  • Max-Forwards

  • Proxy-Authenticate

  • Proxy-Authorization

  • Public

  • Range

  • Retry-After

  • Server

  • TE

  • Trailer

  • Transfer-Encoding

  • Upgrade

  • URI

  • Vary

  • Via

  • Warning

  • WWW-Authenticate

Youve seen how to send XML information out of Flash so that it can be updated in a server-side file. In the next exercise, well use the sendAndLoad method to extend exercise 6 so that the form within the application updates the external file photoGallery.xml .

Putting it all together

Exercise 7: Saving the XML updates from Flash
image from book

In exercise 6, we used a form to update an XML document tree within Flash. In this exercise, well send the updated tree to a server-side page that updates the external XML file. Youll need to have a web server and the .NET Framework installed to complete this exercise. If you prefer to work with PHP, Ive included the resource file updateGallery.php . You could also create your own server-side file to handle the updates. Well start by setting up the environment.

Setting up the environment

  1. If it doesnt already exist, create the folder FOE in the web server. If youre running IIS on Windows, the path to the web server is C:\Inetpub\ wwwroot .

  2. Copy the files updateGallery.aspx, galleryXMLupdate.fla and photoGallery.xml to the FOE directory.

  3. Open the starter file galleryXMLupdate.fla from the FOE folder . This is the completed file from exercise 6. Figure 4-47 shows the interface.

    image from book
    Figure 4-47: Displaying the galleryXMLupdate.fla interface

Youll notice that the interface is populated with the existing gallery names from the XML document. Well need to collect the data from the form to send to a server-side file for processing.

Sending the content from Flash

Well use the sendAndLoad method of the XML class to send the information from Flash to a server-side page. The page will replace the existing photoGallery.xml file with an updated version. It will also send a message back to Flash.

  1. Select frame 1 on the timeline and open the actions layer in the Actions panel with the F9 shortcut key.

  2. Change the update_btn onRelease function as shown here. The new line calls the function updateContent .

     update_btn.onRelease = function():Void {   selectedGallery = gallery_cb.selectedItem.label;   var currentGallery:String;   var comment:String;   var NewPhotoNode:XMLNode;   var NewPhotoCommentNode:XMLNode;   if (selectedGallery != "-- Select --" ){     if (filename_txt.text == "") {       error_txt.text = "Please enter a filename";     }     else if (filename_txt.text.indexOf(".jpg") == -1){       error_txt.text = "Please enter a filename ending in jpg";     }     else {       error_txt.text = "";       comment = comment_txt.text;       for (var i:Number=0; i < RootNode.childNodes.length; i++) {         currentGallery = RootNode.childNodes[i].attributes.         locationName;         if (selectedGallery == currentGallery){           GalleryNode = RootNode.childNodes[i];           NewPhotoNode = photoXML.createElement("photo");           NewPhotoCommentNode = photoXML.createTextNode(comment);           NewPhotoNode.attributes.caption = caption_txt.text;           NewPhotoNode.attributes.filename = filename_txt.text;           NewPhotoNode.appendChild(NewPhotoCommentNode);           GalleryNode.appendChild(NewPhotoNode);  updateContent();  break;         }       }     }   }   else {     error_txt.text = "Please select a gallery before clicking update";   } } 
  3. Add the updateContent function, shown next, to the bottom of the actions layer. The function creates a new XML object called replyXML . It sets the content type for photoXML and sends the complete document tree to the server-side page updateGallery.aspx . The replyXML object receives the response from the server-side page and calls the showReply function.

     function updateContent():Void {   var replyXML:XML = new XML();   replyXML.onLoad = showReply;   photoXML.contentType = "text/xml";   photoXML.sendAndLoad("http://localhost/FOE/updateGallery.aspx",   replyXML); } 
  1. Add the showReply function to the bottom of the actions layer. The function shows either the reply from the server or an error message.

     function showReply(success:Boolean):Void {   if (success) {     trace (this); }   else {     trace ("Error receiving reply");   } } 

Testing the movie

  1. Test the movie from within Flash and enter some values in the form. Figure 4-48 shows the values that I entered.

    image from book
    Figure 4-48: Displaying the form details

  2. Click the Update button and Flash should process the update. Figure 4-49 shows the Output window displayed after the server-side file processes the update. In reality, Id probably change the code so that the message displays in the interface.

    image from book
    Figure 4-49: Displaying the response in Flash

  3. Open the FOE folder.

  4. Open the updated photoGallery.xml file. Figure 4-50 shows the updated contents in XML Spy. Ive highlighted the new <photo> node.

    image from book
    Figure 4-50: Displaying theupdated file in XMLSpy

In this exercise, we used a Flash XML application to add new information to an external XML file. Flash collated the information and generated a new XML node. We used the sendAndLoad method of the XML class to send the XML document tree to a server-side file for processing. We were able to open the XML file and check the updates. You can see the completed file saved as galleryXMLupdate_completed.fla in your resources for this chapter. Ive also included a PHP version galleryXMLupdatePHP_completed.fla.

Points to note from exercise 7

  • As I mentioned earlier, you will need to set the permissions on the FOE folder so that the server-side page has access to write to the folder. If you dont have the relevant permissions, you wont be able to create the XML file on your computer.

  • The server-side page saved the updated file to the current folder, that is, the FOE folder on the web server. You can change the path to save the file anywhere on your computer. You will need to alter the following line within the updateGallery.aspx file:

     xmlDocument.Save(Server.Mappath("photoGallery.xml")); 

For example, to save the file to c:\flash\gallery\ , change the line to read

 xmlDocument.Save("c:\flash\gallery\photoGallery.xml"); 
  • When you entered the details in the form, the Flash movie didnt upload the image file at the same time. Flash cant do this for security reasons. You could use the new FileReference class to browse for the image file and determine the file name. However, the FileReference class still requires a server-side file to upload the file to its new location. You can also copy the file to the new location yourself.

  • When you updated the external XML file, Flash didnt recognize the elements that were originally marked as CDATA. Youll notice that Flash replaced the HTML tags within your file with HTML entities. If you wanted to add markup to the comments, you would also have had to use entities in the TextArea component.

  • You cant test the file updateGallery.aspx on its own in a web browser. If you try to do this, youll see an error as the file relies on content sent from Flash.

image from book
 


Foundation XML for Flash
Foundation XML for Flash
ISBN: 1590595432
EAN: 2147483647
Year: 2003
Pages: 93
Authors: Sas Jacobs

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net