Wednesday, February 16, 2011

Send variables using GET method using AS3 - communicate with PHP, Javascript

Today we will learn how to send variables from AS3 using GET method. This way we can communicate with PHP, Javascript, etc.

Using the GET protocol we can send variables to other pages through the query string, for example:

www.mysite.com/test.html?firstName=Kirill&lastName=Poletaev

If a page receives this information, it can, for example, with Javascript, parse it and get two variables from that line: firstName and lastName.

Firstly, let's create the data in AS3 that we will be sending using this GET method.

var myData:URLVariables = new URLVariables();
myData.firstName = "Kirill";
myData.lastName = "Poletaev";

var myRequest:URLRequest = new URLRequest("http://mysite.com/test.html");

myRequest.data = myData;
navigateToURL(myRequest, '_blank');

As you can see, we create an URLVariables object and create 2 parameters for it - firstName and lastName. Then, we create an URLRequest, where we write the path to the page we want to send our variables to. In my example it's a test.html file with Javascript code in it to parse the variables, but we're not limited to that - we could direct to a php file if we wanted to (then we could get the variables using $_GET['var']).

Here's the code in the test.html:

<html>
<head>
<title>
Test AS3
</title>
<script type="text/javascript">
function getParam(sParamName){
    var Params = location.search.substring(1).split("&"); 
    var variable = "";
    for (var i = 0; i < Params.length; i++){ 
        if (Params[i].split("=")[0] == sParamName){ 
            if (Params[i].split("=").length > 1) variable = Params[i].split("=")[1]; 
            return variable;
        }
    }
    return "";
}

</script>
</head>
<body>

<input type="button" value="get firstName" onclick="alert(getParam('firstName'))"> <input type="button" value="get lastName" onclick="alert(getParam('lastName'))"> 
</body>
</html>

As you can see, there's a function getParam that is used to parse the variables from the query string and return their values.

If we had to communicate with a server-side php file, our php code would look something like this:

<html>
<head>
<title>
Test AS3 PHP
</title>
</head>
<body>
 
<?php
$fullName = $_GET["firstName"]." ".$_GET["lastName"];
echo "Hello, $fullName!";
?>

</body>
</html>

This way we can send variables to other pages and we aren't limited to just one language.

Thanks for reading!

1 comment:

Albert Andrada said...

Really Nice Information,Thank You Very Much For Sharing.
Wordpress Development Company

Post a Comment