Building Web Forms In Flash - Coming Back For More (
Page 5 of 6 )
The
example you just saw submitted the user's input to a PHP script, thereby
redirecting the browser to a fresh page. In case you'd like this result page to
also be generated in Flash, Flash MX includes a new ActionScript function named
sendAndLoad(), which allows you to submit form data to a server-side script and
read the response back into the Flash movie for further processing. This
response can then be used to build a new Flash movie on the fly.
If this
seems like alien technology to you, don't be afraid - it's not very difficult to
do. First, you need to set up your server-side script so that it returns a set
of variable-value pairs as URL-encoded form data - as the following example
demonstrates:
alpha=1&beta=45
These variables can then be read into Flash and used to
assign values to variables within the Flash movie.
Consider the following
revision of the ActionScript code above, which demonstrates the process:
function doSubmit()
{
userData = new LoadVars();
userData.name = name;
userData.species = species;
userData.speciesType = speciesType.getValue();
userData.residence =
residence.getValue();
response = new LoadVars();
response.onLoad = getResponse();
userData.sendAndLoad("register.php", response, "post");
}
function getResponse(result)
{
if(result == true)
{
// use result values
}
else
{
// display error
}
}
In this case, a new instance of the LoadVars() object has
been created, this one designed to hold the variable package returned by the
server-side script. When this response is received by the Flash movie, the
onLoad event handler is triggered, and the getResponse() function
invoked.
Note the difference in the technique used to actually submit the
form data to the server - the previous example used the send() method, which
only submitted the data, while this one uses the sendAndLoad() method, which
both submits data and accepts a response.
The getResponse() function
returns an object, whose properties correspond to the variables returned by the
server-side script. So, if the server-side script returned the string,
color=red&shape=round
which contains the variables "color" and "red", I could
modify the getResponse() function above to use them like this:
function getResponse(result)
{
if(result == true)
{
set("itemInstance.color", result.color);
set("itemInstance.shape", result.shape);
}
else
{
// display error
}
}
In this case, variables within the Flash symbol
"itemInstance" are being set to the values returned by the server-side script
"register.php", via the set() method.