How to get URL query-string variables within Flex application

On flexcoders, someone asked, how to get the URL parameters in a Flex 2.0 application? By URL parameter, I mean the query-string variables, as shown below:

http://yourserver/yourapp.swf?name=Joe&age=22 or http://yourserver/yourapp.mxml?name=Joe&age=22

Note: To get the variables in flex via mxml file, you need server-side compilation of mxml files.

You can get the values of the params using from

mx.core.Application.application.parameters

object, which contains the name-value pairs (hash-map).

For example,

mx.core.Application.application.parameters.name

would return “Joe”, considering above example URL. You can find more information about this in livedocs: http://livedocs.macromedia.com/flex/20beta1/docs/00001300.html

Then someone asked, what if your swf is embedded in custom html wrapper, how to get the query-string params inside swf?

Most of us use ExternalInterface class in Macromedia Flash Player 8(onwards) to invoke some JavaScript functions and extract the value in ActionScript.

I wrote a quick-and-dirty class in ActionScript 3, which would get the values of params from URL query-string for you. You don’t need any extra JavaScript code in HTML. The same logic can be used for any an ActionScript 2.0 running Macromedia Flash Player 8.
QueryString class has following properties:-

  • parameters – an Object which contains the name-value pairs from query-string
  • queryString- String, this contains the entire query-string (url-encoded) name-value pairs.
  • url- String, this returns the complete URL of the wrapper page with query-string.

See demo
Download source files

  • http://blog.circlecube.com Evan Mullins

    Abdul,
    Thanks this is a great site, I’ve learned a lot already. I thought your QueryString class was very intuitive and easy to use. I wanted to let you know I actually liked it so much I ported it back to as2. And I figured I’d share that as well, so it’s at my blog post here, Get Current URL and Query String Parameters to Flash. Just to let you know!
    Thanks again for the class,
    Evan @ Circlecube.com

  • baji

    Hi..i am trying to do fileuplaod from flex to java servlet..problem is request is not coming to servlet..If I use jsp instead of servlet then request is coming to jsp..am not sure what’s wrong with srvlet approach..any help woudl be appreciated
    here is my code:
    here is my servlet
    ……………….
    package com.boa.flex.servlet;
    import java.io.File;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.net.URLDecoder;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileItemFactory;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    /**
    * @author nbkzk5e
    *
    */
    public class UploadFileServlet extends HttpServlet
    {
    /* (non-Javadoc)
    * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
    */
    private static final Log log = LogFactory.getLog(UploadFileServlet.class);
    //@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    // TODO Auto-generated method stub
    super.doGet(req, resp);
    doPost(req,resp);
    }
    //@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    log.info(“am in servlet”);
    log.info(“author”+req);
    File disk = null;
    FileItem item = null;
    FileItemFactory factory = new DiskFileItemFactory();
    Iterator iter = null;
    List items = null;
    ServletFileUpload upload = new ServletFileUpload( factory );
    ServletOutputStream out = null;
    try
    {
    // Parse the incoming HTTP request
    // Commons takes over incoming request at this point
    // Get an iterator for all the data that was sent
    // TODO: Leverage generics
    log.info(“am in servlet”);
    items = upload.parseRequest( req );
    iter = items.iterator();
    // Set a response content type
    res.setContentType( “text/xml” );
    // Setup the output stream for the return XML data
    out = res.getOutputStream();
    out.println( “” );
    // Iterate through the incoming request data
    while( iter.hasNext() )
    {
    // Get the current item in the iteration
    item = ( FileItem )iter.next();
    // If the current item is an HTML form field
    if( item.isFormField() )
    {
    // Return an XML node with the field name and value
    out.println( “” );
    // If the current item is file data
    } else {
    // Specify where on disk to write the file
    // Using a servlet init param to specify location on disk
    // Write the file data to disk
    // TODO: Place restrictions on upload data
    disk = new File( “C:\\”+item.getName() );
    log.info(“am after disk”);
    item.write( disk );
    // Return an XML node with the file name and size (in bytes)
    out.println( “” );
    }
    }
    // Close off the response XML data and stream
    out.println( “” );
    out.close();
    // Rudimentary handling of any exceptions
    // TODO: Something useful if an error occurs
    } catch( FileUploadException fue ) {
    fue.printStackTrace();
    } catch( IOException ioe ) {
    log.info(“io error”);
    ioe.printStackTrace();
    } catch( Exception e ) {
    e.printStackTrace();
    }
    }
    }
    here is web.xml
    ……………..
    XFireServlet
    org.codehaus.xfire.transport.http.XFireConfigurableServlet
    XFireServlet
    /servlet/XFireServlet/*
    XFireServlet
    /services/*
    FileServlet
    com.boa.flex.servlet.UploadFileServlet
    FileServlet
    /action/*

  • http://www.abdulqabiz.com/blog Abdul Qabiz

    @Evans: Thanks. Please feel free to use this code in whatever way you want to.
    @Baji: I can’t see flex code, please post it again enclosed by <pre>yourcode</pre>

  • glenn

    @Steve: I think you aren’t running the code inside a webserver. Try running it on localhost, or place it on your webserver (or install LAMP/WAMP/MAMP for a quick Apache/Mysql environment on you local machine)

  • http://www.nemke.net Nemanja

    Great job Abdul!

  • Jad

    Hi,
    With all those comments I still can’t get it running…
    Here’s my situation:
    Dynamically generated page by Typo3 CMS.
    On this page I have a little Flex application. And this application should detect the language parameter from the URL, wich is L.
    The url looks like this : http://www.domain.com/index.php?id=1125&L=1
    I’ve tried all your solutions… nothing!
    When I launch the flex app from Flexbuilder, I can see that qs.url contains the url. Good. But queryString remains desperatly empty…
    And when I deploy the flex app to the website, then qs.url also remains empty…??
    What did I forgot?? I’m really desperate…

  • Jad

    Hi,
    With all those comments I still can’t get it running…
    Here’s my situation:
    Dynamically generated page by Typo3 CMS.
    On this page I have a little Flex application. And this application should detect the language parameter from the URL, wich is L.
    The url looks like this : http://www.domain.com/index.php?id=1125&L=1
    I’ve tried all your solutions… nothing!
    When I launch the flex app from Flexbuilder, I can see that qs.url contains the url. Good. But queryString remains desperatly empty…
    And when I deploy the flex app to the website, then qs.url also remains empty…??
    What did I forgot?? I’m really desperate…

  • Fernando

    Nice joob ;D

  • http://ndinesh.wordpress.com Dinesh

    Hi, now what is the equivalent of Application.application.url in flash as3 ?? how to get the url in as3?? pls help..

  • dvtin

    Thanks, this article very good, I try successfull, one more thanks.

  • http://www.miketec.org MIke

    I doubt anybody will read this far, but it is much easier to use URLUtil.stringToObject to decode the query string. And it can handle decoding the parameters.

  • Varun

    Hi Abdul,
    I have been a web application developer using JSP and servlets etc. Now i am entering into flex development. Can you point me to some resource that can help me make the transition (Specfically aimed at Java web developers).
    Thanks in advance,
    Varun

  • http://www.reina.com.my Lin

    Hi Mr. Abdul Qabiz
    Can you advice me, what is the Variable or AS set for in the SWF? for both the Name & Hometown according to your SOURCE FILE. Can you show me the FLA?

  • Faisal Rehman

    hi Abdul,
    I have used your class it is awesome and realy greate work.
    But still i have found some problem with this class :) when i am passing values to html it is working fine for both mozila and Internet Explorer.
    and when i am passing values directly to swf like
    http://localhost/myswf.swf?myname=faisal
    in mozila it is working perfect but not working for internet explorer.
    is it possible to pass values to swf in internet explorer or this is limitation of class or am i missing something ?
    Please Help !
    Hope you will reply.
    Thanks

  • Kb

    This helped me, thank you soo much

  • http://www.highcamp.ca SL

    I can’t believe how long I had to search for this, it’s exactly what I needed yet no body on any of the forums could help me. I knew the solution was there but it’s a matter of knowing how to access the variable name.
    Thanks so much,

  • http://vajahatalee.blogspot.com Vajahat Ali

    Nice Article Adul

    • http://www.abdulqabiz.com Abdul Qabiz

      @vajahat: Glad to know, you found it useful. It’s very old one and I believe, it can updated to use better technique.

  • Olga S.

    Thank you very much, I started to use your class right away.

    • http://www.abdulqabiz.com Abdul Qabiz

      @olga:

      Glad to know, it helped you.

      -abdul

  • Simon

    Hi Abdul,

    That’s great !

    Here is a very interesting use of your code:

    I have two Applications. MyAppWidget is a small swf used to navigate to different main applications on different servers.

    In MyAppWidget:

    var url:String = “”
    url += navigateEvent.applicationBaseURL;
    var request:URLRequest = new URLRequest(url);
    var variables:URLVariables = new URLVariables();
    variables.email = _modelLocator.loginAttempt.username;
    variables.pwd = _modelLocator.loginAttempt.password;
    request.data = variables;

    request.method = URLRequestMethod.GET;

    try {
    navigateToURL(request);

    Im MyMainApp:
    I use your wrapper and it work great ! However, as you can see my parameters are email and encrypted pwd over https, so I would like to use the URLRequestMethod.POST (not GET) to hide it (it’s best practice too) and in this case the script doesn’t work anymore…

    Any suggestion ?

    By the way, I have a recommendation: It will be great to create a js that can simply be include in the standard flex wrapper (html) and “push” flashvar on demand. I’m so disappointed that it’s not out of the Flex 3 box ! maybe in Flex 4 ? My understanding is that BrowserManager can only read fragment (everything after # character by using browserManager.fragment) and not parameters (from GET or POST function in HTML)

    Simon

  • http://sijpkes.net Paul Sijpkes

    Thanks Abdul! I could not get the flashvars to work with my custom app but this has solved it for me. No need to pass any variables to the EMBED tag via PHP! So easy! Thanks.

  • http://www.nicoweb.fr/ nicoweb.contact

    Hi,

    thanks abdul for this great article, i knew about flashvars, how to get them, etc, but it seems this process is faster and easier ;) thks for the details :)

    @+++

  • http://twitter.com/rajranjan12 Rajnish

    yuytuytuytu

  • http://www.mmdguru.com/ Thomas

    How do I use this class?

    Like this:

    var qs:QueryString = new QueryString();
    var id:int = qs.parameters.id;

    Will this give me the id number in this url:

    http://www.domain.com/index.html?id=5

    Nice if it’s so easy=)

    • http://www.abdulqabiz.com/blog/ Abdul Qabiz

      That’s right, it should work that way. I wrote this class long time back and have not tested it against latest browsers, flash player and flex framework.

      Please let me know, if you confirm it still works.

    • Thomas

      It worked like a charm in Firefox 3 and up + explorer 8 and up=)

      Good job man!

  • Sachin Dev Tripathi

    Hi abdul,
    I have passed the ImgId in UrlRequest and then i used navigateToUrl to open new window. i opened application i am using Application.application.parameters.ImgId but it is not working although ?ImgId=1 is displaying in url. i have not used your QueryString.as class. It is must to use?

    Please let me know what i am doing wrong?

    Thanks
    Sachin

  • Sachin Dev Tripathi

    Its excellent…works perfectly..i am exactly looking for this..Thanks you very much..

    Thanks again

    Warm regards
    Sachin dev tripathi

    • Sachin Dev Tripathi

      Could you please advise to Adobe Flex team to make a class ‘URLParser’ or ‘QueryString’ like this? It must be added with the SDK. If your solution is not much complecated so why they had not think about it to already implement with SDK? :x

      Thanks
      Sachin
      sachindevtripathi@gmail.com

  • arthipesa

    Thank you abdul, this code is what I was needed to know.

  • http://devprez.com/ devPrez

    You are a champ, thanks!!

  • Pingback: ActionScript3 : QueryString | Erko Bridee

  • jaguilar

    Thank you for writing this post!

  • Gideon

    Thx for the example. Was very helpful!

  • http://www.expertsfromindia.com/flex-development-india.htm Flex development india

    Its a great site, I’ve learned a lot already. I thought your QueryString class was very intuitive and easy to use. I wanted to let you know I actually liked it so much I ported it back to as2. And I figured I’d share that as well, and it also done well in with the input strings and its quite the systemic anomoly.
    Excellent work,

    • http://www.abdulqabiz.com/blog/ Abdul Qabiz

      That’s great. I am glad you liked it.

      You can drop the AS2 version’s link here, so some people might find it useful.

  • Dave Hopkins88

    Hi !
    Firstly thanks for this great post, works a treat. I have it working fine in my application. However when i try to iFrame my application into another website i cant get it to work.

    ANy idea on how i can do this ?

    • http://www.abdulqabiz.com/blog/ Abdul Qabiz

      Hi Dave

      Thanks for your comment and feedback, I need to figure out why it’s not working.

      Please share details, if you happen to find out the problem and solution.

      Thanks

      -abdul

  • Azmat

    Very useful info, Thanks

  • kgntech

    Excellent
    information i got here,thanks its very helpful to me,keep up blogging.