I know this is frequently asked, but I have looked all over the internet to find the mistake I'm making with the code I've used to send and receive data from AS3 to PHP and viceversa. Can you find the mistake? Here is my code:
AS3:
import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequestMethod;
import flash.events.Event;
submitbtn.addEventListener(MouseEvent.CLICK, sendData)
function sendData(event:MouseEvent):void
{
var loader : URLLoader = new URLLoader;
var urlreq:URLRequest = new URLRequest("http://[mydomain]/test.php");
var urlvars: URLVariables = new URLVariables;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlreq.method = URLRequestMethod.POST;
urlvars.uname = nametxt.text;
urlvars.apellido = aptxt.text;
urlvars.email = emtxt.text;
urlvars.cedula = cctxt.text;
urlvars.score = scoretxt.text;
urlreq.data = urlvars;
loader.addEventListener(Event.COMPLETE, completed);
loader.load(urlreq);
}
function completed(event:Event): void
{
var loader2: URLLoader = URLLoader(event.target);
trace(loader2.data.done);
resptxt.text = event.target.data.done;
}
PHP inside of [domain]/test.php:
<?php
$username = $_POST["uname"];
$apellido = $_POST["apellido"];
$cedula = $_POST["cedula"];
$email = $_POST["email"];
$score = $_POST["score"];
print_r($_POST);
if (!($link=mysql_connect(databasemanager,username,password)))
{
echo "Error conectando a la base de datos.";
exit();
}
if (!mysql_select_db(database,$link))
{
echo "Error seleccionando la base de datos.";
exit();
}
try
{
mysql_query("insert into scores(name,lastName,email,document,score) values('$username','$apellido','$email','$cedula','$score')",$link);
print "done=true";
}
catch(Exception $e)
{
print "done=$e->getMessage()";
}
echo "done=true";
?>
Thanks for your answers.
Your AS code seems to be right. So the problem might be in PHP. Please test first with this PHP file:
<?php
echo "test=1&done=true";
?>
This should then let your movie trace "true".
You then should debug your PHP. print_r($_POST); destroys your output of course. May be you did forget to remove this debugging statement :-)
#Jesse and #Ascension Systems, check the docs for URLVariables: http://livedocs.adobe.com/flash/9.0_de/ActionScriptLangRefV3/flash/net/URLVariables.html
Try
submitbtn.addEventListener(MouseEvent.CLICK, sendData);
function sendData(event:MouseEvent):void
{
var urlreq:URLRequest = new URLRequest ("http://[mydomain]/test.php");
urlreq.method = URLRequestMethod.POST;
var urlvars:URLVariables = new URLVariables();
urlvars.uname = nametxt.text;
urlvars.apellido = aptxt.text;
urlvars.email = emtxt.text;
urlvars.cedula = cctxt.text;
urlvars.score = scoretxt.text;
urlreq.data = urlvars;
var loader:URLLoader = new URLLoader (urlreq);
loader.addEventListener(Event.COMPLETE, completed);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(urlreq);
}
public function completed (event:Event):void{
var variables:URLVariables = new URLVariables( event.target.data );
resptxt.text = variables.done;
}
Updated the completed function... and corrected missing bracket.
First of all, change this line of code:
trace(loader2.data.done);
to this:
trace(loader2.data);
You're outputting raw text from php, so your data object in flash is just gonna be raw text. It's not an object with .done attached to it. If you want to have a data structure then you need to create some XML or something inside PHP, print that out and then cast loader2.data as XML, like so:
var returnedData:XML = new XML(loader2.data);
However, if your XML is not formed correctly, you'll create an uncaught error in flash and crash your app, so make sure you use try/catch statements.
Related
In Adobe AIR Dektop, I wrote some code to read JSON data from our VPS, I think my AS3 codes are true but I'm not sure about the PHP codes. Adobe Animate console is empty after I run project.
This program have access to other sites and after run i can read data from them, but from our VPS i can't.
AS3:
import flash.events.*;
import flash.net.*;
var loader: URLLoader;
var request: URLRequest;
function load(): void {
request = new URLRequest("212.73.150.148/asphp.php");
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.load(request);
}
function onError(e: Event): void {
trace(e.target.data + "READING DATA FROM VPS ERROR");
}
function onComplete(e: Event) {
trace(e.target.data);
var json: Object = JSON.parse(e.target.data);
trace("json.DATA1 = ", json.DATA1);
trace("json.DATA2 = ", json.DATA2);
}
load();
PHP:
<?php
$arr = array ('DATA1'=>"111",'DATA2'=>"222");
header('Content-Type: application/json');
echo json_encode($arr);
?>
I used wrong URL value "212.73.150.148/asphp.php" after change to "http://212.73.150.148/asphp.php" it worked.
I'm just trying out PHP and AS3 in Flash CS6. I want a few strings to be passed from PHP to Actionscript3 and store them in an array. Is this possible?
Currently I'm doing this. My PHP code is
<?php
echo "one,two,three,four";
?>
and AS3 code is:
var myRequest:URLRequest = new URLRequest("please7.php");
var myLoader:URLLoader = new URLLoader();
myLoader.load(myRequest);
myLoader.dataFormat = URLLoaderDataFormat.TEXT;
myLoader.addEventListener(Event.COMPLETE, onLoaded);
function onLoaded(event:Event):void {
var variables:String = event.target.data;
trace(variables);
var arr1:Array = new Array();
arr1 = variables.split(",");
trace(arr1);
}
This gives me this output:
<?php
echo "one,two,three,four";
?>
If I use myLoader.dataFormat = URLLoaderDataFormat.VARIABLES; instead of myLoader.dataFormat = URLLoaderDataFormat.TEXT; ..I'm getting this error
Error: Error #2101: The String passed to URLVariables.decode() must be
a URL-encoded query string containing name/value pairs.
I want the output to be a simple [one two three four]
What am I doing wrong?
You can do like following, it will be passed as a query-string
In PHP
<?php
echo 'q=' . htmlentities($your_data);
?>
In AS3
var urlLoader:URLurlLoader = new URLurlLoader();
urlLoader.dataFormat = URLurlLoaderDataFormat.VARIABLES;
urlLoader.addEventListener(Event.COMPLETE, onComplete);
urlLoader.load(new URLRequest("somefile.php"));
function onComplete (event:Event):void {
trace (urlLoader.data.q.toString());
}
I'm trying to pass some variables from php to flash, im using this actionscript code:
public function gameOver(score:Number)
{
totalScore.text = score.toString();
var scriptVars:URLVariables = new URLVariables();
scriptVars.score = score;
var scriptLoader:URLLoader = new URLLoader();
var scriptRequest:URLRequest = new URLRequest("checkScores.php");
scriptRequest.method = URLRequestMethod.POST;
scriptRequest.data = scriptVars;
scriptLoader.load(scriptRequest);
scriptLoader.addEventListener(Event.COMPLETE, handleLoadSuccessful);
scriptLoader.addEventListener(IOErrorEvent.IO_ERROR, handleLoadError);
}
function handleLoadSuccessful(e:Event):void
{
trace("Scores Loaded");
var vars:URLVariables = new URLVariables(e.target.data);
nickname1.text = vars.nickname;
score1.text = vars.score;
}
function handleLoadError($evt:IOErrorEvent):void
{
trace("Load failed.");
nickname1.text ="error";
}
And this php code:
<?php
... some code for the mysql connection and select sentence ...
$topScores = mysqli_query($con, $topScores);
$topScores = mysqli_fetch_array($topScores);
echo "&nickname=$topScores[nickname]&score=$topScores[score]";
?>
both runs without errors, the problem is that what i get on flash aren't the variables values but the name of the variables, in other words what i get on vars.nickname is
$topScores[nickname]
and for vars.score
$topScores[score]
If i run the php alone i get this:
&nickname=jonny&score=100
which are the actual variable values i'm trying to get, any help would be greatly appreciated.
I think you may just be loading up the php file as a text file from flash. Can you change the following line:
new URLRequest("checkScores.php");
to something like:
new URLRequest("http://localhost/checkScores.php");
or whatever you see in the browser address bar when you "run" it as you said in your question.
I'm completely new to Flash and AS3. I've Googled around an cannot find anything on this topic.
I have some code that posts an image to a php file:
var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var jpgURLRequest:URLRequest = new URLRequest("http://127.0.0.1/gdipORG/takeImage.php");
jpgURLRequest.requestHeaders.push(header);
jpgURLRequest.method = URLRequestMethod.POST;
jpgURLRequest.data = byteArray;
navigateToURL(jpgURLRequest, "blank");
Problem is, for the actual posting to take place, I have to navigate to the actual url (see last line of code)...
I want to be able to post the data to the url without having to navigate to it. Any ideas?
Use a URLLoader right after your existing code:
//Existing code
var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var jpgURLRequest:URLRequest = new URLRequest("http://127.0.0.1/gdipORG/takeImage.php");
jpgURLRequest.requestHeaders.push(header);
jpgURLRequest.method = URLRequestMethod.POST;
jpgURLRequest.data = byteArray;
//KILL THIS LINE navigateToURL(jpgURLRequest, "blank");
//Add these (UNTESTED CODE):
var sendJPGLoader:URLLoader = new URLLoader();
sendJPGLoader.dataFormat = URLLoaderDataFormat.BINARY;
sendJPGLoader.addEventListener(Event.COMPLETE, sendJPGToServerComplete);
sendJPGLoader.addEventListener(IOErrorEvent.IO_ERROR, sendJPGToServerIOError);
//Try to send image
sendJPGLoader.load(jpgURLRequest);
function sendJPGToServerComplete(evt:Event):void {
//Request was sent to server succesfully
//Optionally check server response
// var serverResponse:String = String(evt.target.data);
}
function sendJPGToServerIOError(evt:Event):void {
//Failed
}
At the top of your code don't forget to import:
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
I think I got them all :)
I am new to action script 3.0. Help me to understand how can I load data with URLLoader.
So, I have an aplication like:
var PATH:String = "http://www.somesite.com/myFirstPage.php?a=10&b=20";
var urlRequest:URLRequest = new URLRequest(PATH);
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete);
urlLoader.load(urlRequest);
function urlLoader_complete(evt:Event):void {
some_result = urlLoader.data;
}
php script looks like:
<?php
//retrieve GET params
int c = a + b; //a and b come from GET request
return "{{"result_equal":"20"}}"; //result in JSON
?>
I don't really understand how JSON result from .php page gets in my URLLoader object. Help me by simple example, please. Thanx!
You need a few things here. First off, you'll need a JSON library, because somehow it isn't built into Flash, even with their modified E4X core:
https://github.com/mikechambers/as3corelib
This should give you the following bits of code:
import com.adobe.serialization.json.JSON;
function urlLoader_complete(e:Event):void
{
var loader:URLLoader = URLLoader(e.target);
var some_result:Object = JSON.decode(loader.data);
}
Now... your PHP code is a mess. The best way to create JSON is to just use the json_encode function:
$retVal = array('result_equal'=>20);
echo json_encode($retVal);
You will want to use this project: https://github.com/mikechambers/as3corelib
Example usage:
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.rpc.events.ResultEvent;
import com.adobe.serialization.json.JSON;
private function onJSONLoad(event:ResultEvent):void
{
var rawData:String = String(event.result);
var arr:Array = (JSON.decode(rawData) as Array);
var dp:ArrayCollection = new ArrayCollection(arr);
grid.dataProvider = dp;
}
]]>
</mx:Script>
<mx:HTTPService
id="service"
resultFormat="text"
url="http://weblogs.macromedia.com/mesh/mashedpotato.json"
result="onJSONLoad(event)" />
PHP code should looks like this:
$result = array("result_equal" => 20);
return json_encode($result);
So, this is what I get: Please, say whats wrong, what good! Thanx1
package
{
import data.*;
import flash.errors.IOError;
import flash.events.Event;
import flash.events.*;
import flash.net.*;
public class UserInfoProxy
{
public static const GET_USER_INFO:DataCallConfigVO = new DataCallConfigVO( "COMMON", 'GET_USER_INFO', true, null, null);
public function UserInfoProxy()
{
trace("Start request");
var request:URLRequest = new URLRequest("http://www.avrora.com.localhost/myservlet.php");
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.addEventListener(ProgressEvent.PROGRESS, progressHandler);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
loader.load(request);
}
private function completeHandler(event:Event):void
{
var loader:URLLoader = URLLoader(event.target);
trace("Complete");
trace("completeHandler: " + loader.data);
}
private function progressHandler(event:ProgressEvent):void
{
trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
}
private function securityErrorHandler(event:SecurityErrorEvent):void
{
trace("securityErrorHandler: " + event);
}
private function httpStatusHandler(event:HTTPStatusEvent):void
{
trace("httpStatusHandler: " + event);
}
private function ioErrorHandler(event:IOErrorEvent):void
{
trace("ioErrorHandler: " + event);
}
}
}
And this is my PHP code, that must return JSON data:
<?
//here I can process all input GET, POST params, database etc...
$someJSONresponse = "{'username':'yozhik', 'age':'18'}";
//here just echo result and it will be automatically downloaded??
echo $someJSONresponse;
?>