When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips

Sections:
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
XML Info
Information:
Feedback
Author an Article
ASP ASP.NET ASP FAQs Message Board Feedback
Print this page.
Published: Wednesday, March 26, 2003

Get Your Charts in a Flash!, Part 4

By Pallav Nadhani


  • Read Part 1
  • Read Part 2
  • Read Part 3

  • In Part 3 we looked at creating the various frames needed for the FlashCharts. In this part we'll look at reading and parsing the XML document that contains the chart data.

    - continued -

    Loading and Parsing XML Document
    Macromedia Flash MX provides an excellent native XML Object to deal with XML data. Using this object, one can load, send, and parse XML documents inside Flash. For our application, we just need to load the XML data from the URL provided to the graph (using the OBJECT/EMBED method which we had discussed earlier), parse it and then use the parsed information to build the graph. Specifically, all our XML loading and parsing activities would be contained in three frames, namely: LoadXML, LoadingXML, and ParseXML.

    LoadXML is the frame where we instantiate the command to load the XML document. Open up the Actions Panel for Actions Layer > Frame LoadXML and enter the following action script:

    //Instantiate the XML document
    XMLDoc = new XML();
    
    //Make the control go to the function fnloaded as soon 
    //as the XML document is loaded
    XMLDoc.onLoad = fnloaded;
    
    //Now, get the path of the XML document(can be from an Asp file) 
    //that has to be loaded. The path is passed to the movie by the 
    //page in which this movie is embedded.  So, if it is embedded in 
    //an ASP page, we would embed the movie as 
    //        "FlashCharts.swf?DataUrl=ProvideData.asp"
    xmldocurl = _root.dataurl;
    
    //If no path has been provided, then just load a default 
    // XML file. This part is optional.
    if (xmldocurl.length<1) {
    	xmldocurl = "Data.xml";
    }
    
    //Load the XML document
    //If you want the document NOT to be CACHED, you can append the 
    //time at the end of the file name
    XMLDoc.load(xmldocurl+"?curr="+getTimer());
    
    //In this method, a random number is added at the end of the file 
    //name - example. ProvideData.asp?curr=23443
    //Thus whenever a request is sent to the server (via the 
    // browser), it interprets it as another URL 
    XMLDoc.load(xmldocurl);
    
    
    function fnloaded() {
    	//This function will be invoked when the XML file is loaded.	
    	gotoAndPlay("ParseXML");
    }
    
    
    play();
    

    The above ActionScript first initializes an instance of the XML document, storing it in the local variable XMLDoc. We then instruct Flash that as soon as the XML document has been completely downloaded in the movie, the function fnloaded should be invoked. Next, we get the path of the XML document that has to be loaded. The path is passed to the movie by the page in which this movie is embedded as we had earlier seen using the OBJECT/EMBED method. The dataurl passed to the Flash movie from the ASP page in the format FlashCharts.swf?dataurl=Data.asp is now accessible in Flash via _root.dataUrl.

    The following if statement, which is optional, specifies that a default XML file should be loaded in the event that no dataurl path has been provided. We invoke the load method of the XML object to load the document. We append the time at the end of the file name so that it is not cached.

    The function fnloaded, which is invoked when the XML file is loaded, simply sends the control to the ParseXML keyframe wherein the XML document will be parsed to retrieve the information. Finally, the play() command keeps the movie playing, which moves the Flash movie on to the next keyframe.

    For More Information on ActionScripting...
    If this is the first time you've seen Macromedia's ActionScript, you may want to take a few minutes to familiarize yourself with the syntax and style before performing these steps on your own. There are a number of great ActionScripting Web sites available, such as ActionScripts.org and FlashKit.com's ActionScripting tutorials.

    Recall that our next keyframe is LoadingXML - the frame that is displayed until the XML document has been completely downloaded by Flash. We need to show the user some splash/loading screen while the data is being fetched from the server. So, to achieve this, create a new layer called Loading Contents and on the frames of this layer, place anything which you want your users to see while the data is being loaded. The picture until now should look something like:

    Also, in the Actions Panel of this frame, we just ask Flash to keep on playing, by adding the following one line of ActionScript: play();. When the play() function is called in the LoadingXML keyframe the control is transferred to the keyframe ParseXML. In this frame, we first check if the XML document has been successfully downloaded or not. If it hasn't been downloaded, we send the control back to LoadingXML to display the loading Frames. If it has been downloaded and it doesn't contain any errors, we continue with the parsing process by invoking the custom function parseXML();. However, if there is an error in parsing the XML file we transfer the control to a keyframe XMLError, which displays an error message to the user stating that the XML received was malformed.

    The following ActionScript, which should be placed in the ParseXML keyframe, accomplishes these tasks:

    //Now if the document is loaded and it's not empty
    if (XMLDoc.loaded and XMLDoc.hasChildNodes) {
       //Check for errors in XML document
       if (XMLDoc.status == 0) {
          //If no errors present then parse it
          parseXML();
       } else {
          //If errors present, show an error message
          gotoAndPlay("XMLError");
       }
    } else {
       //If the document has not been loaded, we just send the control 
       //a li'l back to waste some time
       gotoAndPlay("LoadXML");
    }
    

    The following function, parseXML helps in parsing the XML and retrieving the data from the XML document. Parsing the XML document using the XML object in Flash is similar to the XMLDocument() class in ASP.NET or the MSXML Parser in ASP. We have to traverse down the tree using the methods and properties exposed by the XML object.

    function parseXML() {
       //This functions parses the XML Data passed to it.
       //cldNodes array will contains the child nodes of the XML 
       //Doc passed to it.
       cldnodes = new Array();
       cldnodes = XMLDoc.childNodes;
       
       //Num will contain the count of datasets passed to the movie
       num = 0;
       
       //Dataset will contain the data childnodes
       dataset = new Array();
       
       //DataName will contain the x-axis name(or value) of the data sets
       dataname = new Array();
       
       //DataValue will contain the y-axis value of the data sets
       datavalue = new Array();
       
       //dataLink will contain the hot-spots
       dataLink = new Array();
       
       //Iterate through the first level children of the XML Doc
       for (j=0; j<=cldnodes.length; j++) {
          //Check if the node Name is Graph i.e., the data set 
          //belongs to graph
          if (cldnodes[j].nodeName.toUpperCase() == "GRAPH") {
             //Get the chart type to be shown
             chartType = cldnodes[j].attributes.chartType;
             
             //Get the caption of the graph
             caption = cldnodes[j].attributes.caption;
             
             //Get the x-axis name
             xaxisname = cldnodes[j].attributes.xaxisname;
             
             //Get the y-axis name
             yaxisname = cldnodes[j].attributes.yaxisname;
             
             //Now, we get the dataset
             dataset = cldnodes[j].childNodes;
             
             //We iterate through the data set
             for (k=0; k<=dataset.length; k++) {
                //If the node name is Set i.e., a graph data set, 
                //then we retrieve and collect the values
                if (dataset[k].nodeName == "set") {
                   //Get the x-axis name
                   dataname[num] = dataset[k].attributes.name;
                   
                   //Get the value
                   datavalue[num] = dataset[k].attributes.value;
                   
                   //Get the link
                   dataLink[num] = dataset[k].attributes.link;
                   
                   //Increment counter
                   num = num+1;
                }
             }
          }
       }
       play();
    }
    

    The parseXML() function starts by creating an array to hold the childnodes of the XML document. XMLDoc.childNodes returns a pointer to the root element of the XML document. Next, we declare a variable num to store the count of the datasets passed to the movie (via the XML document). We then iterate through the first level children of the XML Doc to search for the <graph> element.

    If the element is the <graph> element, then we access the graph attributes. To access the attributes we use the attributes collection in Flash. First, we get the chartType of the graph and store it in the variable chartType, and then the caption and so on. Next, we iterate through the data set. A check is made if the node name is set - i.e., a graph data set. If the element is <set> then we retrieve and collect the values. Finally, we redirect the control to the setDefaults frame (the play() command does it for us).

    The setDefaults frame is used to set the chart type. Open the Actions Panel for Layer Actions > Frame setDefaults and enter the following ActionScript:

    //In this frame, we detect the chart type specified
    //Based on chart type, go to the required frame
    //Perform a case-insensitive check'
    switch (chartType.toUpperCase()) {
     case "LINE" :
       gotoAndPlay("LineChart");
       break;
     case "BAR" :
       gotoAndPlay("BarChart");
       break;
     case "PIE" :
       gotoAndPlay("PieChart");
       break;
     default :
       //If a wrong/no chart type has been specified
       //By default select Bar Chart as the default one
       gotoAndPlay("BarChart");
    }
    

    In the above ActionScript we first detect the chart type to be displayed by default. The chartType attribute of the <graph> element tells the graph as to which graph (bar, pie or line) should be displayed by default. Recall that there are three values which this attribute can take: bar, line or pie. You can assign any of these three values to the chartType attribute to determine which type of graph should initially be used. If no value is supplied for this attribute, the default value is taken as bar.

    Next, we need to create a function setChart(chartInstance) that will later help us manipulate the chart. In this function, we set the chart's parameter and the data.

    function setChart(chartInstance) {
       //This function sets the properties and the data of a 
       //particular chart instance
       //---------INPUT PARAMETERS------------
       // chartInstance: String representation of the chart movie clip's 
       //                instance name
       //-------------------------------------
       //First, get a reference to the chart object
       movChart = eval(chartInstance);
    
       //Clear the chart's contents
       movChart.removeAll();
    
       //Set it's title
       movChart.setChartTitle(caption);
    
       //Set x-axis and y-axis name
       movChart.setXAxisTitle(xAxisName);
       movChart.setYAxisTitle(yAxisName);
    
       //Now, set the data
       for (i=0; i < num; i++) {
          //Create a new temporary object
          chartItem = new Object();
    
          //Set the object's label property
          chartItem.label = dataName[i];
    
          //Set the object's value property
          chartItem.value = dataValue[i];
    
          //Add the object to the chart's rendering stack
          movChart.addItem(chartItem);
       }
    }
    

    We also need to create a function called gotoUrl that will later act as the event handler for the chart onRelease function. That is, when the user clicks on the bars, lines or pies of a chart, this function will be invoked.

    function gotoUrl(objectRef, recordIndex) {
       //This function acts as the onRelease event handler for 
       //all the charts
       //INPUT PARAMETERS -------
       //objectRef - the object which called this function
       //recordIndex- Index of the chart data set which wass clicked.
       //-----------------
       //Go to the URL of the dataset having index as recordIndex (if the 
       //URL for that dataset has been specified)
       if (dataLink(recordIndex) != "" || dataLink(recordIndex) != null || 
              dataLink(recordIndex) != undefined) {
          //go to the URL
          getURL(dataLink[recordIndex]);
       }
    }
    

    Now, that we have the defaults for the graph calculated and stored in variables, it's time to apply them. In Part 5 we will set the various chart components in place.

  • Read Part 5!


  • ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article