Flex & Javascript Basics - Using ExternalInterface

Skill

Flex & Javascript Basics - Using ExternalInterface

Posted in:

Now that we have gone over Flex and PHP its time to get some client side interaction going on with Javascript. This tutorial will show you how to call javascript functions from flex and flex functions from javascript. There is a really nice example of the use of this on Google Finance, as well as a number of other google sites.

The application below gives you a little taste of what can be done between javascript and flex. You can add people to the flex application using the small form on the bottom right through javascript, and if you select a person in the flex app and click the "Javascript Display" button you will get the info back out to the small form on the top right.

Get Adobe Flash player
Data coming into Javascript
Name: 
Age: 
Sex: 
Data sending from Javascript
Name:
Age:
Sex:

The very first thing to do is to set up a basic flex application - the code below represents close to the simplest one possible. This sets up an application with specified height and width.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
   layout="absolute" width="482" height="348">
</mx:Application>

The next step in the process is to setup a simple flex interface with no functionality built in. We put a panel into our application and give it a title. Next we add the DataGrid object which we will bind our data to. In the DataGrid we add a couple columns (DataGridColumn), take notice to the dataField names as they will define the keys for our incoming data. So in this case our data coming in should have values from 3 keys: "Name", "Age" and "Sex". We also add a button, which will later be used to call a Javascript function on our page. Lastly we add a label to give us a quick status update when sending the data to Javascript. We also give each of the ui components an id so that we can refer to them later. All this code goes inside the application tags.

<mx:Panel id="pnlMain" x="10" y="10" width="462" height="328"
   layout="absolute" title="Simple Javascript Interaction">
  <mx:DataGrid id="dgPeople" x="10" y="10" width="422" height="229">
    <mx:columns>
      <mx:DataGridColumn headerText="Name" dataField="Name"/>
      <mx:DataGridColumn headerText="Age" dataField="Age"/>
      <mx:DataGridColumn headerText="Sex" dataField="Sex"/>
    </mx:columns>
  </mx:DataGrid>
  <mx:Button x="10" y="256" label="JavaScript Display" id="butJSDisplay" />
  <mx:Label x="149" y="260" id="lblMessage"/>
</mx:Panel>    

At this point you should be able to compile and run to see your small interface.

Ok, next up after this is just getting some data into our DataGrid and we are going to do this with a small bit of Actionscript. First, we attach a function call to our DataGrid's initialize event. So our new DataGrid opening tag looks like the one below.

<mx:DataGrid id="dgPeople" x="10" y="10" initialize="initDG()" width="422" height="229">

Now to go along with the event we need to write the actual function that it is referring to. First thing we need to do is add a script tag to our application. Then we can start writing the function. We also add an import call so that we can use ArrayCollection.

Inside the function "initDG" we do a little bit of data creation. We create an array for the data, and then push a few items onto the array - we use {key1: "value1", key2: "value2"...} syntax to add an associative array for each item. Now we need to make sure our keys match the ones we used for our DataGridColumns so the DataGrid knows what columns to associate with what values. Next thing done is to create an ArrayCollection to bind to and stick the array in it. And last thing we do is bind our dgPeople (DataGrid) to it and set the initial selected index. So this gives us the following code for our script and this code goes right below the application opening tag.

<mx:Script>
 <![CDATA[
   import mx.collections.ArrayCollection;
   
   public function initDG():void
   {
     var people:Array = new Array();
     people.push({Name: "Charlie", Age: "23", Sex: "Male"});
     people.push({Name: "Brandon", Age: "23", Sex: "Male"});
     people.push({Name: "Mike", Age: "23", Sex: "Male"});
     people.push({Name: "Caroline", Age: "23", Sex: "Female"});
     var peopleCollection:ArrayCollection = new ArrayCollection(people);
     dgPeople.dataProvider = peopleCollection;
     dgPeople.selectedIndex = 0;
   }
 ]]>
</mx:Script>

Ok you again should be able to compile and run the application, and now there should be data in your DataGrid. Next up is sending this data to Javascript. This is pretty easy to do. To start off, we need to add a click event to our button to call a Actionscript function. Below is the new modified button tag.

<mx:Button x="10" y="256" label="JavaScript Display"
   id="butJSDisplay" click="jsDisplayPerson()"/>

Now to make this button work we need to add that Actionscript function. This starts to get into the fun stuff now - to call Javascript functions in Flex we us the External Interface api. You can learn more information about it on the Flex Documentation Site. Basically it allows us to build wrappers to call Javascript functions from Flex and vice versa.

We add our Actionscript function in the Script tags and we also need to add an import statement for "flash.external.*". There is not much to the function itself: first we check if there is a External Interface available (basically this makes sure we are in a html page). If we are we can make the magic happen, with a call to ExternalInterface.call we can send information to a Javascript function called "displayPerson" whose argument is the selectedItem in our DataGrid. Now this should send an array of data of the selected item to Javascript. To learn more about what can be sent to Javascript check out this Adobe Documentation page. Last we update the status label saying that we sent the data. Otherwise, if the external interface is not available we display an error message in the label. Now our script tag looks like this:

<mx:Script>
 <![CDATA[
   import mx.collections.ArrayCollection;
   import flash.external.*;
   
   public function initDG():void
   {
     var people:Array = new Array();
     people.push({Name: "Charlie", Age: "23", Sex: "Male"});
     people.push({Name: "Brandon", Age: "23", Sex: "Male"});
     people.push({Name: "Mike", Age: "23", Sex: "Male"});
     people.push({Name: "Caroline", Age: "23", Sex: "Female"});
     var peopleCollection:ArrayCollection = new ArrayCollection(people);
     dgPeople.dataProvider = peopleCollection;
     dgPeople.selectedIndex = 0;
   }

   public function jsDisplayPerson():void
   {
     if (ExternalInterface.available)
     {
       ExternalInterface.call("displayPerson", dgPeople.selectedItem);
       lblMessage.text = "Data Sent!";
     }
     else
     {
       lblMessage.text = "Error sending data!";
     }
   }
 ]]>
</mx:Script>

Now we get to write a bit of javascript code to display the person that is being sent to us from flex. So in a set of Javscript tags we create our displayPerson function - remember, the name has to match perfectly to what we told ExternalInterface.call function in flex to call. The first thing we do in our Javascript function is make sure we are not getting a null object and if it is null we display an alert. Then we just use the object passed as a javascript object and reference the appropriate datagrid columns using javascript object property syntax. All I do with them is display the values in a few table cells, but at this point you can do anything with the data that you want. So in our html script tags we get some code like this:

function displayPerson(person)
{
  if(person == null)
  {
    alert("Please select a person, or maybe I screwed up.");
  }
  else
  {
    document.getElementById('nameDisplay').innerHTML = person.Name;
    document.getElementById('ageDisplay').innerHTML = person.Age;
    document.getElementById('sexDisplay').innerHTML = person.Sex;
  }
}

So then if we add a little bit of html that looks like what I have below the javascript from above should work and populate a few table cells. You should be able to embed the flex movie, but notice we need to have the allowScriptAccess property in our object and embed tags for the movie before the "Javascript Display" button works. You can check the source of this page if you need more info.

<table>
  <tr>
    <td>Name:</td>
    <td id="nameDisplay" style="width:150px;">&nbsp;</td>
  </tr>
  <tr>
    <td>Age:</td>
    <td id="ageDisplay" style="width:150px;">&nbsp;</td>
  </tr>
  <tr>
    <td>Sex:</td>
    <td id="sexDisplay" style="width:150px;">&nbsp;</td>
  </tr>
</table>

Now you should be able to call any javascript functions from your Flex applications using the above technique. The next thing we are going to do is setup our flex application so that flex functions can be called by javascript via ExternalInterface.

The first thing we need to do is add some code to our application startup to initialize what flex functions will be accessible through external calls. We add code to our application tag to fire a function on the initialize event. The following code is the new application tag, it simply calls an actionscript function when the initialize event is fired.

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
   width="482" height="348" initialize="initApp()">

Now we can write the initApp actionscript function. This function will check if the ExternalInterface is available to keep from getting errors when running in the regular 'ole flash player. Then it adds a callback for an actionscript function, this function will be referred to externally as "addPerson" (the first argument to addCallback) and will map to the internal function called addPerson (the second argument to addCallback). The initApp function should then look like the code below, which is added in our actionscript script tags.

public function initApp():void
{
  if (ExternalInterface.available)
    ExternalInterface.addCallback("addPerson", addPerson);     
}

Now the only thing left to do in our flex application is create the function "addPerson", which will add people to our DataGrid. This function takes three arguments: a string for the name, age, and sex of the new entry. Now to add an item we take the current Items in DataGrid cast them as an ArrayCollection and add a new item using the data we passed in. Again this is an actionscript function so you need to put it in the actionscript script tags.

public function addPerson(name:String, age:String, sex:String):void
{
  (dgPeople.dataProvider as ArrayCollection).addItem({Name: name, Age: age, Sex: sex});
}

Now that we have our mxml and actionscript written we can create some html and javascript to use our new external flex function. The javascript function we are going to make will just grab a few values from a couple input items on our html page and then we will call the flex function using those values as arguments. In order to call the flex function, we use another function called getFlexApp('FlexJSTutorial'). I will go over this in just a second. So what we add to our javascript tag is the following.

function addPerson()
{
  var name = document.getElementById('txtName').value;
  var age = document.getElementById('txtAge').value;
  var sex = document.getElementById('selSex').value;
  getFlexApp('FlexJSTutorial').addPerson(name, age, sex);
}

So now you are wondering about this getFlexApp function - well this is the function that actually returns us the flex app that is on the page. I originally had an issue getting the embedded object but found the suggested solution on Adobe's site here. This function takes into account various types of browsers. The one thing you need to do is make sure your object and embed tags for your flash movie have an id and name. These are required for getting the flex application. So the following function goes in the javascript tag:

// This function returns the appropriate reference,
// depending on the browser.
function getFlexApp(appName)
{
  if (navigator.appName.indexOf ("Microsoft") !=-1)
  {
    return window[appName];
  }
  else
  {
    return document[appName];
  }
}

The last thing are going to do is create the html inputs that we use in our javascript addPerson function. This includes two input text boxes and one input select with two options one for "Male" and one for "Female". Nothing special about these, also we have a button which we use to call our javascript function when the onclick event occurs. I put all these in a table for a little bit of organization:

<table style="border-spacing:5px;">
  <tr>
    <td style="border-style:none;padding:0px;">Name:</td>
    <td style="border-style:none;padding:0px;">
      <input id="txtName" type="text" />
    </td>
  </tr>
  <tr><td style="border-style:none;padding:0px;">Age:</td>
    <td style="border-style:none;padding:0px;">
      <input id="txtAge" type="text" />
    </td>
  </tr>
  <tr><td style="border-style:none;padding:0px;">Sex:</td>
    <td style="border-style:none;padding:0px;">
      <select id="selSex" style="width:100px;">
        <option value="Male">Male</option>
        <option value="Female">Female</option>
      </select>
    </td>
  </tr>
  <tr>
    <td colspan="2" style="border-style:none;padding:0px;">
      <input type="button" id="butAddPerson"
       onclick="addPerson()" value="Add Person" />
    </td>
  </tr>
</table>

And that about wraps it all up. If you have any questions at all please leave them in a comment, and I will try and help you out.

Below is the full code for the mxml file.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
   width="482" height="348" initialize="initApp()">
  <mx:Script>
   <![CDATA[
     import mx.collections.ArrayCollection;
     import flash.external.*;
   
     public function initDG():void
     {
       var people:Array = new Array();
       people.push({Name: "Charlie", Age: "23", Sex: "Male"});
       people.push({Name: "Brandon", Age: "23", Sex: "Male"});
       people.push({Name: "Mike", Age: "23", Sex: "Male"});
       people.push({Name: "Caroline", Age: "23", Sex: "Female"});
       var peopleCollection:ArrayCollection = new ArrayCollection(people);
       dgPeople.dataProvider = peopleCollection;
       dgPeople.selectedIndex = 0;
     }
   
     public function addPerson(name:String, age:String, sex:String):void
     {
       (dgPeople.dataProvider as ArrayCollection).addItem(
           {Name: name, Age: age, Sex: sex});
     }
   
     public function initApp():void
     {
       if (ExternalInterface.available)
          ExternalInterface.addCallback("addPerson", addPerson);       
     }
   
     public function jsDisplayPerson():void
     {
       if (ExternalInterface.available)
       {
         ExternalInterface.call("displayPerson", dgPeople.selectedItem);
         lblMessage.text = "Data Sent!";
       }
       else
       {
         lblMessage.text = "Error sending data!"
       }
     }
   ]]>
 </mx:Script>
  <mx:Panel id="pnlMain" x="10" y="10" width="462" height="328"
     layout="absolute" title="Simple Javascript Interaction">
    <mx:DataGrid id="dgPeople" x="10" y="10" initialize="initDG()"
       width="422" height="229">
      <mx:columns>
        <mx:DataGridColumn headerText="Name" dataField="Name"/>
        <mx:DataGridColumn headerText="Age" dataField="Age"/>
        <mx:DataGridColumn headerText="Sex" dataField="Sex"/>
      </mx:columns>
    </mx:DataGrid>
    <mx:Button x="10" y="256" label="JavaScript Display"
       id="butJSDisplay" click="jsDisplayPerson()"/>
    <mx:Label x="149" y="260" id="lblMessage"/>
  </mx:Panel>    
</mx:Application>

EDIT: You can check out all the html code needed here.

Bruce
07/21/2007 - 07:45

Wow! Excellent tutorial on using JavaScript and Flex. Thanks for providing such a well written and easy to follow example.

reply

Bruce
07/21/2007 - 08:29

Here are a few notes for anyone who wants to create the Flex application and HTML page to duplicate the example given in this excellent tutorial.

1. When you create a new Flex project, make a note of the name you give your Flex project. For example I called my Flex project FlexToJavaScript. You will need this name for one of the JavaScript functions (see below).

2. After you have copied the Flex app source code in the tutorial into your own Flex project run your Flex app to ensure the basic data grid displays with the data.

When you run a Flex app in Flex Builder, Flex Builder uses a file named index.template.html to create the HTML page that includes your compiled Flex app (a Flash SWF). The index.template.html is in the html-template folder of your Flex project. You can add HTML markup and JavaScript functions to the index.template.html file and that way that markup will be present in the HTML file Flex Builder creates.

3. Copy the HTML markup for the two tables given in the tutorial (the one table that displays the data send from Flex to the HTML page and the other table that encloses the input fields to get data to send to the Flex app). I pasted the HTML for these two tables into the index.template.html just after the ending of the tag. Save index.template.html and rerun your Flex app. The two tables should appear below the DataGrid.

4. The JavaScript functions given above can also be copied into the index.template.html file. Just copy all the JavaScript code given in the tutorial to an area inside the block that is right after the closing tag. Be sure you don't overwrite the JavaScript that is already inside that block. Save the index.template.html file and rerun your Flex app to make sure you didn't overwrite something. Everything should work ok and you should be able to select a data grid row and then click on the button and the row's data should appear in the table.

5. In the index.template.html locate the JavaScript function addPerson. Inside this function is a command getFlexApp('FlexJSTutorial'). Change FlexJSTutorial to the name you gave your Flex project (my Flex project was named FlexToJavaScript so that is what I used instead of FlexJSTutorial). The name you gave your Flex project becomes the value for the id attribute of the embed and object tags (which are used to display your compiled Flex App [the SWF]).

6. Save index.template.html and rerun your Flex app. You should now be able to enter data into the input fields and send that data to Flex where it will appear in the DataGrid.

reply

Bruce
07/21/2007 - 08:35

It looks like some of instructions above got stripped out. Here are missing words.

3. ...I pasted the HTML for these two tables into the index.template.html just after the ending of the iframe tag.

4. ...area inside the javascript block that is right after the closing style tag in the head section

reply

The Fattest
07/21/2007 - 09:38

Bruce, thanks for the comments and the helpful information on various parts of the tutorial.

reply

Pankaj Tiwari
08/07/2007 - 23:19

It's really nice interactive tutorial

reply

Niks
08/09/2007 - 06:45

I am new with flex and this is my first application.

I have created FLEX project named "Connection" in Flex Builder 2 for above Tutorial.

The mxml file is Connection.mxml.
And I have putted all java script code to index.template.html.

I don’t know what path should I write to viewSourceURL?

Can anybody help me out?

Thanks in Advance

reply

Niks
08/09/2007 - 06:56

full path is
C:\Documents and Settings\Nikunj\My Documents\Flex Builder 2\Connection\Connection.mxml

reply

Niks
08/09/2007 - 07:06

I got it ..its running..

Really a very nice tutorial

reply

The Fattest
08/09/2007 - 08:01

Glad to hear you got it running. Really you don't have to have the viewSourceURL; this is just a nicity that I like to do so people can see the actual source behind the examples.

If you need any other help feel free to ask, Niks.

reply

Niks
08/10/2007 - 01:51

Thanks for co-operation

reply

lmendoza
08/09/2007 - 13:14

Excellent tutorial.!!!

reply

Vishal
08/17/2007 - 08:18

First of all thanks for sharing this great example. I am new in flex. I have tried it and it works for me fine. Now my desire is to call the flex function from java script but I need to call the function from a function of JavaScript class created in a JS file.

I have tried the code in example for that. It works fine for firefox, but for IE it is not working. Can any one give me any idea about that?

Same way is it possible to call a java script function in js file from flex?

reply

Reyonne
08/20/2007 - 14:17

i don't know the reason why because when i try this thing it crashes my browser (IE). but when i switched to my old fscommands, it worked again. They call the same commands and parameters. Do you know where did i go wrong?

Thanks.

reply

Girish
08/24/2007 - 22:58

Hi
My mxml file is called ExtInterface.mxml.When I compile this project a file ExtInterface.html is created in the bin folder of the project.Can I place the html code in this file or does it have to be in the index.template.html ?

reply

Megha
08/25/2007 - 03:57

i have a problem for retriving the new data from database.when i click on the edit link that time edit page will be displayed and then click on hte save button that time data will not save.

reply

Praba
09/05/2007 - 05:47

Hi thanks for sharing this greate concept. keep on posting like this.

Thanks and Regards
Praba.S

reply

Ganesh
09/06/2007 - 00:43

Thanks for giving nice tuitorials

reply

Domnic
09/19/2007 - 11:26

Hi, I tried to run this code in Flex Builder 2. I followed every set of instructions mentioned here. I can see the datagrid, I can see the input fields and the buttons. But when I enter my data the datagrid does not get updated. When I click on the Javascript display, it does puts a status "Data sent" I cannot see the reaction.
I am a newbie can someone help me here please..?
thanks
D

reply

John Chang
10/03/2007 - 10:39

Domnic,

I had the same problem, but then realized it was this function that was causing the problem:

// This function returns the appropriate reference,
// depending on the browser.
function getFlexApp(appName) {
  if (navigator.appName.indexOf ("Microsoft") !=-1) {
    return window[appName];
  } else {
    return document[appName];
}

According to Adobe's documentation at
http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Book_Parts&file=19_External_Interface_178_3.html

it doesn't seem we need the function to detect browsers. So I simply deleted the function, and used 'FlexJSTutorial' as the app name, and it worked. ;-)

reply

Prince
10/04/2007 - 01:30

hi,
im new to flex can u tell me how to connect flex to sqlserver
using .net

reply

Swetha
10/12/2007 - 06:32

Can you give the complete code of html.

Some other example if available.

Not sure of using

reply

The Fattest
10/13/2007 - 14:01

swetha yeah sure just give me a day and I will add an edit to the post with the entirety of the html and everything.

reply

The Fattest
10/16/2007 - 08:28

I added a link to the html page with all the javascript and html/css code used. You can then just view the source or save the page to get it all.

reply

Inn
10/15/2007 - 06:19

OK

reply

Tim
11/05/2007 - 04:57

Hi there,

I've got a question especially for the Fattest. First of all i want to thank you for the great tutorial. Its really helpful but i want to get rid of the grey activation border. How is that possible? Thank you!

reply

The Fattest
11/05/2007 - 12:40

Tim, I assume your talking about IE's click to activate thing. This can be avoided by using JavaScript to embed the .swf file. A quick post explaining it can be found here from FindMotive.com.

Let me know if this isn't what you need.

reply

Tim
11/06/2007 - 04:03

Yeah Thanks! It works. I used hundreds of examples but all didn't work in combination with your tutorial but this one did. Thank you man!

reply

Lance
11/20/2007 - 15:04

Thanks for the tutorial, very helpful, extremely well-written.

reply

Pankaj Tiwari
12/05/2007 - 06:18

Hi thank's for such an interactive tutorial.

I have one doubt regarding call to action-script method using javascript (using 'ExternalInterface' api).

The example works fine usually. But some time it reports javascript error saying the method of 'action-script' which we are calling in javascript is not a function or property.

Kindly help me out of this problem.

Thank's

reply

The Fattest
12/06/2007 - 08:40

Pankaj,

I am not sure why you would be getting this, I haven't experienced that problem before. What brower/version are you using? Another option is to try the Flex-Ajax Bridge if you are using Flex 3. You can check this out over at Adobe Labs.

reply

Pankaj Tiwari
01/09/2008 - 01:42

Hi Fattest,
thanks for you advice. I was using IE v 6.0. I figured out the problem.The javascript method to invoke action-script method had some problem. Now it's working fine. Thank's once again !

reply

Himanshu
12/05/2007 - 12:20

Its really a nice tutorial, and very nicely explained too. Its really helpfull.

reply

Doreen
12/17/2007 - 00:38

Hi! What a simple but interactive app you have! :)
Thanks for sharing~!
Btw, are you able to do up a tutorial regarding on how to remove and edit the datas after adding? For example, using removeItemAt() method etc.
I really need help in this.

Thanks alot in advance! :)

reply

Sagnik
12/20/2007 - 04:40

It's a nice well described tutorial. Thanks...........

reply

Jimmy
12/21/2007 - 15:10

Thanks for a great tip. I am .Net user and I got it working on Mozila but not on IE. In .Net, we always have to include form tag if any form elements(i.e. textbox, dropdown, etc). Then that "getFlexApp" function becomes useless. I did notice that "window[appName]" is returning embed object. So I initialized embed object, but it's not recognizing the Flex function. Has anyone encounter similar problem as mine? And anyone has resolved this issue?

reply

Buddy
01/22/2008 - 11:20

Actually, my problem is this. I have a datagrid where there are 3 columns. I need to populate one column from the value that I enter into a text box and hit the Add Row button. The data for the other 2 columns can be dummy data. How do I achieve this in Flex. I am populating the other rows in the data grid through an array.

Thanks !

reply

Raj
02/12/2008 - 08:24

A very helpful, interactive tutorial !!

Thanks

reply

Oscar Alderete
02/25/2008 - 19:19

Thank you for your great article. When some amazing technology as Flex can interact with other like JS, then it can be more powerful even. I'm starting with Flex, but after read you article I'm thinking about ways to mix Flex with Ajax and some dynamic content with PHP by myself. Thank you again.

reply

Jason Deegan
03/04/2008 - 07:43

Nice work...very helpful to the newbie! Thank you.

reply

Chuck
03/04/2008 - 17:14

It is not working for me. I always get "undefined" in the javascript function.

Flex is sending a string but javascript is getting undefined object.

Please help!!

reply

Chuck
03/04/2008 - 17:29

nevermind I found it. hehe. sorry for the bandwith waste.

reply

Jeffry Houser
03/11/2008 - 15:33

Thank you! This was very helpful in getting the Flex documentation examples to work!

Once I added and used your "getFlexApp" function, I was able to get the sample working.

reply

Kronus
03/12/2008 - 15:09

Thanks for providing some excellent information and maybe you can help me with an issue I'm having sending an array to flex from Javascript.

I'm basically using:

var flexApp = FABridge.fab.root();
flexApp.myActionScriptFromJavascript(someArrayComing);

Which is sent an array with the key & value as in your example, except that I write out the entire array via PHP returning values like so:
[{SHOWS: "some show", GENDER: "Female", etc...}] -- but I receive an error in the JavaScript error console that has an arrow pointing directly after the first ":" character following the word SHOWS.

The strange thing is that if I copy & paste the data generated from the PHP file into the JavaScript function by replacing the word someArrayComing, then it loads the info into the datagrid with no errors and no issues.

So my question is why would data that I can copy and paste not work when being passed into a param?

Thanks in advance

reply

Shobhit Deep
03/26/2008 - 04:53

Hey! I'm into .NET and MS Technologies since a long.... Just started with Flex and found your tutorial very helpful in understanding the communications between JS and Flex.... Thanks and Keep it Up....

reply

Zeeshan
03/28/2008 - 22:03

Nice tutorial. keep posting such stuff.

reply

Gilbert
04/09/2008 - 11:24

Great tutorial. Thanks for sharing.

I have a question:
How you pass the whole table data at once?

I am creating a Flex app that displays a ColumnChart, and the data comes via JavaScript, so I need to pass the whole array collection or an XML file to Flex.
Any suggestions?

Gilbert

reply

Bhaskar
04/10/2008 - 11:05

Good example,easily understandable keep on posting any new examples with good logic.

reply

Rano
04/28/2008 - 00:27

thx

reply

Jim
05/01/2008 - 03:41

Thanks for the tutorial, I'm having great fun with it :)

I've been using Bruce's method above for modifying the html wrapper by changing my index.template.html file. I've noticed that in certain circumstances flex builder will stop generating your wrapper file even though you have 'Generate HTML wrapper file' checked in properties. If this happens you need to uncheck it, apply the settings then go back into properties and switch it on again.

Its very odd but also frustrating and I hope this helps anybody with the same problem.

reply

Jim
05/01/2008 - 05:13

Make sure to backup the html template if you do this though

reply

Mike
05/03/2008 - 03:18

amazing tut!
good job it was very helpful!

reply

Eddie
05/05/2008 - 16:17

I am getting an
"1120: Access of undefined property ArrayCollection"
error here:

public function addPlayer( player_name:String,
                           jersey_: String,
                           age_:String):void
{
  /*error on next line */    
  (RosterList.dataProvider as ArrayCollection).addItem(
    {playerid: 0,
     playername: player_name,
     jersey: jersey_,
     age: age_
    }
   );
}

Am trying to add extra fields that are not being passed
to the function. But if I take out the extra field,
playerid, I still get the error.

reply

The Fattest
05/06/2008 - 08:08

This sounds like you don't have the import statement in your code.

import mx.collections.ArrayCollection;

reply

Jay bharat
05/14/2008 - 02:50

The best example on array I proud of You , dear.
Jay Bharat..........

reply

Anonymous
08/21/2009 - 13:47

http://bharatbaba.com/blog/

reply

Andrian
05/21/2008 - 22:19

I'm using Flex IDE 3
I have an ActionScript Project.
I can call JS from AS but not the other way around. Does anybody know what could be the cause.

Thank you

reply

Mukesh
06/05/2008 - 07:45

I have to need exactly this type of communication between flex and java Script,but i need
Select a few records on the grid and launch a browser popup window (using a URL method). The purpose is to pass the students that are selected from this Flex application to the browser window call.

reply

Mike
06/09/2008 - 07:35

Nice tutorial. I am new to Flex and was wondering how to interact between Flex and JSP. Well done! (btw...works on FlexBuilder 3).

reply

John
06/12/2008 - 08:04

This is excellent tutorial. Thanks for your knowledge sharing. Thanks to Bruce for step by step process to proceed with it.

reply

John
06/12/2008 - 08:07

Question to The Fattest,
can you please give me any link for database connectivity using flex for J2EE server application

Thanks in advance.

reply

Scott
06/13/2008 - 07:00

I am trying to figure out how to run my jsp files through a flex application. Can someone help me with this?

reply

Anonymous
06/20/2008 - 05:22

its a really good tutorial.

reply

Liceven
06/22/2008 - 02:37

great!
It is really helpful...
Thanks very much.

reply

Djibril
06/24/2008 - 18:20

i found it so cool

reply

Ramon
06/26/2008 - 19:37

Aaaaaaaaaaawesome!

reply

Michael
06/30/2008 - 05:37

Thanks for sharing.
Now I got it.

reply

Shadab
08/01/2008 - 04:16

Executing the code given by you is raising the following error
SecurityError: Error #2060: Security sandbox violation: ExternalInterface caller

Can you help me with fixing this?

reply

Senthil
08/05/2008 - 06:18

Nice Job.
Simply Superb

reply

Gaurav
08/11/2008 - 03:54

Good example!!But how can we do the same thing for the chart components in flex by passing the run time data in form of XML in html text box ??

reply

Tobias
08/11/2008 - 08:27

Hi,
nice tutorial. Everything is working great with my Firefox, but I can't get the addPerson() function working with IE. I tried it with Flex 2 and Flex 3.

I tried calling the Flex function without getApp like John Chang suggested in comment 19, but then Firefox and IE aren't able to use addPerson.

Does anyone have any suggestions?

reply

Tobias
08/15/2008 - 08:49

Hi, it's me again. I did change the javascript like this.

function getFlexApp(appName)
{
  if (navigator.appName.indexOf ("Microsoft") !=-1)
  {
    if (BrowserVersion = IE7 or newer)
      return document[appName];
   
    return window[appName];
  }
  else
  {
    return document[appName];
  }
}

reply

Sayali
10/16/2008 - 07:45

Very explainatory example.
But I want to call a java script function from another html file instead of index.template.html.
How do I that?

reply

Sudhanshu
11/05/2008 - 01:58

superb example
and nicely explained also.

reply

Adrian
11/13/2008 - 21:25

Great tutorial. Straight to the point! This gave me all the details I needed to start building Gears based Flex apps.

reply

Pramod
11/28/2008 - 03:47

Hi,

This is a very good article on integration of Flex with javascript. Lucid and good example illustration!!

reply

Tom Graham
12/03/2008 - 02:35

Brilliant tutorial. Helped me a lot with a Flash Ajax integration.

reply

James
12/05/2008 - 02:32

Awesome tut!
I know the thread is old but anyone know a better way of sending an a larger array (more than one record) to flex rather than looping? right now I am just reading a table and looping it to send more than one record at a time. (calls flex at the end of every row to add that item)Anyone know a better way of sending a datagrid in asp to flex? (Im using it to supply a datagrid and make a chart based on a selection that creates a temp table for session only queries)

reply

James
12/12/2008 - 08:43

Jamessooo I figured it out how to parse an array from vb to javascript then to the flex app, but for some reason the data displays and then the application refreshes and wipes the data out, anyone know why that might happen?

reply

James
12/16/2008 - 06:31

just incase anyone reads my blog spam, the problem was using an asp:button which triggers a postback page refresh. refresh removes the added javascript I was writing to the page, I just added a second html input button made visible by the asp:button action and that fixed it. Again thanks for the tut

reply

Alok Mishra
12/25/2008 - 23:40

Good example But how can we do pie chart ,i dont understand how to implemented in pai chart please give detail

reply

Jamil Haddadin
01/10/2009 - 08:28

am getting the following error when i try to call the flex function from the JS:

Microsoft JScript error: “testJavaScript” is undefined

where testJavaScript is the ID of the object tab where i place my swf file.

BTW it is really a nice tutorial.

reply

suvarna
03/18/2009 - 04:55

How to connect flex to java program to run ? I need the connectivity from flex to java

reply

The Fattest
03/18/2009 - 08:52

Well if you are talking about connecting to a java server check out BlazeDS it is a technology that allows fro easy messaging and remoting to java using Flex and Adobe AIR.

reply

Highlander
04/06/2009 - 04:40

Hello!

This is nice work and it works, but only in the bin-debug folder. Have you got any idea why? I set the allowScriptAccess to 'always', the allowNetworking to 'all' in the html-wrapper. And in the code: flash.system.Security.allowDomain("*"), but still nothing if I export it to another directory. I use FlexBuilder.

reply

The Fattest
04/06/2009 - 12:47

Well, what is the error you are getting?

reply

Highlander
04/08/2009 - 01:20

The swf couldn't reach the javascript and vica versa. It runs only in the bin-debug directory of the flexbuilder project. There was a simple: object doesn't support this or it isn't a function (in IE and in FF).

reply

Ben
04/08/2009 - 10:26

I seem to have the same problem.
When I test the app, only the communication from flex to js works, not the other way around.
Even if I test it from the bin-debug folder.

reply

The Fattest
04/09/2009 - 09:27

What version of flex are you using? Also have you made any modifications to the code?

reply

Andrei
04/09/2009 - 08:37

Hi
Very nice tutorial

Only I have a problem: when I try to pass data from js to swf ... is not working .. any help?

reply

Highlander
04/23/2009 - 07:22

In the C:\Documents and Settings\USERNAME\Application Data\Macromedia\Flash Player\#Security\FlashPlayerTrust directory there is a file named flexbuilder.cfg. In this file can be found directory names, where your program works. How can I override this? Because it's not nice that way.

reply

nirmal..............
04/27/2009 - 01:37

its gud

reply

madhu
05/07/2009 - 06:54

I have been using flex sdk. I have been able to make Connection.swf from Connection.xml. But now can anybody tell me how will I include this .swf file with html file?

reply

Anonymous
06/03/2009 - 08:51

I am new to Flex. It is really helpful and nice tutorial. But the communication from AS to JS and viceversa is working only, if we are executing the sample from bin-debug folder. I am trying to run the example from tomcat server, application is loading properly but its not communicating from AS to JS and the reverse. Actually I want to run this using Tomcat, any help on this?

reply

Ashish
07/13/2009 - 05:21

This is very good example of flex + javascript. I appreciate it.

reply

Nvrk
08/25/2009 - 03:14

I am new to flex. I am running top example in flex builder-3. when i run the application I am getting only DataGrid. I am not getting HTML. Please help me. Thanks in advance.

reply

Rajeev sharma
08/31/2009 - 03:08

I am working on Weblogic Portal 10.2.I need to do some stuff later on Flex with Weblogic Portal.
So please let me know how can I start learning the Flex
Please proivde me the URLs to install/configure/examples the Flex on the system.

reply

Roshan Mutha
11/25/2009 - 01:14

Great Example to start with ....Thanks a Lot

reply

Nico
12/16/2009 - 14:11

Hi The Fattest,
have you tried to use your example with AJAX?
I experience following problem:
- I am loading the content (object/embed definition) via a script with AJAX
- I am then pasting the result with JQuery's function html() into an element in the HTML DOM
- What happens now, is that I can call JS from AS, but every call from JS to AS results in an error that the object doesn't support this method or attribute (this happens only in IE browsers 6,7,8. Firefox works).

Has anybody an idea how to solve this problem?

reply

BB
01/14/2010 - 11:27

We got the same problem as you have. Have you fixed that problem?

reply

Terry
12/29/2009 - 15:26

Need some help. Trying to add export to excel logic to a flex component that will be packaged as a SWC and used by our business layers. I don't know where to put the javascript to launch excel so that it will be included in the SWC and available to all users of this component.

reply

kolo
01/29/2010 - 21:14

hi,

I want to copy to clipboard text from Rich TextEditor using rollOver the button. It is not possible to do this only with flex:( How to implement JS button in Flex3 apllication to this... Someone can help?

reply

shri
03/04/2010 - 17:14

copied the code exactly but can't send javascript data to flex...was able to send flex data to javascript.

good work in any case,
shri.amin@gmail.com

reply

shri
03/04/2010 - 19:54

fixed it...i was using the app name 'FlexJSTutorial'
i had named my app something else

reply

FlexChump
04/02/2010 - 14:33

There is some great examples in
http://www.itomes.com/#/60124012457Hello_Flex_4

reply

FlexChump
04/02/2010 - 14:36

Just seen this document too, good example of Flex and Java working
http://www.itomes.com/#/362032935540flex3withjava

reply

Steve
06/09/2010 - 04:01

Hi,

This is working fine when I run this from flex builder.
I am getting an error when I copy html, swf file to my server.

Can you please help me how can move it to my server (html, swf file)?

Thanks,
Steve

reply

Steve
06/09/2010 - 04:03

The error is object doesn't support this property or function.

reply

Slutsky Vadim
06/09/2010 - 04:53

Very good tutorial!

reply

beachgce
06/11/2010 - 05:19

Hi,

Can any one let me i try this method and able to pass the value but i am not able to pass a url from java script to flex and show the image in flex can any one help me how to do this.

The thing is

I need to send a url and need to capture the url to display the image in flex

thank you for the tut hope u may help regarding my issue..

One more thing if i am send an array of object from java script to flex can i seprate the arry object in flex please help me
thnak you.

reply

Puneet Chopra
08/10/2010 - 12:53

Thanks for such a nice and explanatory examples. But i have one question on this. If I have my (html including javascript) file and flex file on same location means same hierarchy then Javascript able to call Flex function. But when i put my flex file on some other location and using this file through HTTP then Javascript not able to call Flex function and giving 'Unexpected Javascript Error'. Request to you please help me to sort out this issue. You can contact me on - puneet1030@gmail.com

thanks..

reply

The Fattest
08/10/2010 - 12:59

I'm not sure that I understand what you're trying to do. But, the javascript and flex have to be on the same page, imagine the flex piece is just another html object. If it hasn't been rendered on the page you don't have access to it. Let me know if I'm off base here.

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.

Sponsors