How do I integrate Flash with Php - php

I want to integrate my flash file with php code. I got the below code from
http://www.kirupa.com/developer/actionscript/flashphpxml_integration2.htm
function lv(l, n, t, e, f) {
if (l == undefined) {
l = new LoadVars();
l.onLoad = function () {
var i;
n.htmlText = "";
if (t == undefined) {
n.htmlText += "<b>" + this["title" + e] + "</b><br>";
} else {
for (i = 0; i < this.n; i++) {
n.htmlText += "<a href='" + this["link" + i] + "'>" + this["title" + i] + "</a><br>";
}
}
};
}
l.load(f);
}
lv(sites_txt, "cycle", null, "sites.php");
I did all the steps given in that forum but while running that code i got error Like
1180: Call to a possibly undefined method LoadVars.
Warning: 1060: Migration issue: The method LoadVars is no longer supported. For more information, see the URLVariables class, the URLRequest.urlVariables and URLRequest.postData properties, and the URLLoader.dataFormat property..
1136: Incorrect number of arguments. Expected 5.
I am new to the flash scripting please guide me how to troublshooting these

Your example code was in AS2, here's how you send and receive data from and to PHP using AS3 using:
URLRequest
URLLoader
URLVariables
Here's a quick class I have made for you:
package
{
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.net.URLVariables;
import flash.net.URLRequestMethod;
import flash.events.Event;
public class PHPData extends Object
{
/**
* Sends data to a PHP script
* #param script A URL to the PHP script
*/
public function send(script:String, vars:URLVariables):void
{
var req:URLRequest = new URLRequest(script);
req.data = vars;
req.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
loader.load(req);
// listeners
loader.addEventListener(Event.COMPLETE, _complete);
}
/**
* Called when a response has been received from a PHP script
* #param e Event.COMPLETE
*/
private function _complete(e:Event):void
{
var vars:URLVariables = new URLVariables(e.target.data);
var i:String;
for(i in vars)
{
trace(i + ": " + vars[i]);
}
e.target.removeEventListener(Event.COMPLETE, _complete);
}
}
}
With this, you can send data to a given PHP script in the format of URLVariables.
URLVariables are easily prepared like so:
var vars:URLVariables = new URLVariables();
vars.myvar = "some value";
vars.myothervar = 30;
Here's a quick example I have mocked up for you which sends a string to PHP, then PHP sends back the string hashed as MD5 and also has a timestamp attached as a secondary value.
var php:PHPData = new PHPData();
var vars:URLVariables = new URLVariables();
vars.myvar = "marty";
php.send("http://projectavian.com/md5.php", vars);
Your output for this will be something similar to:
response: bb3761a33402b4f82806178e79ec5261
time: 1306133172
Just alter the _complete method in the PHPData class to handle your response data as required :)
I'll throw this in because your question has the mysql tag..
All you need to do is your standard INSERT and SELECT queries in the PHP script and encode your result into this format:
var=1&other=2&more=three
So you could have..
<?php
mysql_connect(/* ?? */);
mysql_select_db(/* ?? */);
// INSERT example
$thing = mysql_real_escape_string($_POST["thing"]);
mysql_query("INSERT INTO table VALUES('','$thing')");
// SELECT for response
$id = mysql_real_escape_string($_POST["uid"]);
$query = mysql_query("SELECT * FROM table WHERE id='$uid' LIMIT 1");
// send response
$r = mysql_fetch_assoc($query);
echo 'fname=' . $r["first_name"] . '&lname=' . $r["last_name"];
?>

Related

ActionScript 3 error Invalid JSON parse input

I'm trying to send data to a PHP file via JSON but i'm getting an error when trying to JSON the data.
I'm pretty sure i'm doing this right. Any suggestions ?
Here's my ActionScript 3 code :
var dataToSend:Array = new Array();
var data:Object = new Object();
data.callFunction = "getQuestion";
data.numberOfQuestions = "1";
dataToSend.push(data);
trace(data);
var variables:URLVariables = new URLVariables();
variables.data = JSON.stringify(dataToSend);
var url:String = "myurl";
var request:URLRequest = new URLRequest(url);
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.load(request);
loader.addEventListener(Event.COMPLETE, requestComplete);
And my PHP code :
if $data[ "callfunction" ] = "getQuestion";
{
echo("Sent");
}
Your ActionScript 3 code looks fine but you have some problems in your PHP's one.
Let's see that.
The if statement in PHP is like the AS3's one :
&lt?php
if( condition )
instruction;
?&gt
The equality operator is the == and not the assignment one ( = ).
As you have sent your data using the POST method, you can use the PHP's $_POST array to get it.
Then, as you have sent it on JSON format, you can decode it using the decode_json() function in your PHP side.
So your PHP code can be like this for example :
<?php
if(isset($_POST['data']))
{
$data = $_POST['data'];
$json_data = json_decode($data);
if($json_data[0]->callFunction == "getQuestion")
{
echo("Sent");
}
}
?>
Then you can get the response of your PHP script in your AS3 requestComplete function :
function requestComplete(e:Event): void
{
trace(URLLoader(e.target).data); // gives : Sent, for example
}
...
Hope that can help.

accessing parsed JSON (generated via php) in native Actionscript3 (Flash)

Okay, here goes. I'm sure I'm only missing a small thing somewhere.
I'm trying to do a little Highscore System for my game and thus I have a php script on a webspace for the programm to access (I have literally 0 experience with php):
<?php
$json = json_encode($_REQUEST);
$fileSave = fopen("processdata.txt", "a+") or die ("Can't create processdata.txt");
fwrite($fileSave, $json);
fclose($fileSave);
print($json);
?>
processdata.php
then, in actionscript, I juse this code to access the file and parse it:
//set variables to send to the php script
var variables:URLVariables = new URLVariables();
variables["name"] = "Player1";
variables["points"] = 123;
//set request to load php script
var request:URLRequest = new URLRequest("processdata.php");
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, httpRequestComplete);
loader.load(request);
//php script finished
function httpRequestComplete(_e:Event){
//load processdata.txt
var uLoader:URLLoader = new URLLoader();
var uReq:URLRequest = new URLRequest("processdata.txt");
uLoader.addEventListener(Event.COMPLETE, getProcessdata);
uLoader.load(uReq);
}
//loading of processdata.txt finished
function getProcessdata(_e:Event){
var rawData : String = _e.target.data;
//convert the input string in readable JSON
rawData = rawData.split('"').join("\\\"");
rawData = "\"" + rawData + "\"";
//convert into JSON
var proData:Object = JSON.parse(rawData);
}
here is what processdata.txt looks like (for example)
{"name":"Player1","points":"123"}{"name":"Player2","points":"234"}
this is then converted in my AC into this (to make it readable for the JSON.parse):
"{\"name\":\"Player1\",\"points\":\"123\"}{\"name\":\"Player2\",\"points\":\"234\"}"
Now, how to I access the parsed JSON String? I tried all of those and nothing works:
proData.name;
proData[name];
proData["name"];
proData[0];
proData[name[0]];
for (var obj : String in proData){
obj;
}
Any help is appreciated. Doesn't matter where you find a possibility to make this work (PHP, AC3, JSON, etc)
Also, if you have a simple possibility for me to change my php in a way that it creates xml instead of php, I can do the rest from there, I get my Code to work with a XML File.
Thanks in advance.
You should know that your JSON content is not valid and that's why you can get nothing from it in the ActionScript side.
As you are saving players scores, you can store your data as an array :
[
{
"name": "Player1",
"points": "123"
}, {
"name": "Player2",
"points": "234"
}
]
but to get that, you've to edit your PHP code like this, for example :
<?php
$json_file = 'scores.json';
$new_score = $_REQUEST;
if(file_exists($json_file))
{
// get stored scores
$scores = json_decode(file_get_contents($json_file));
} else {
// create an empty array to store scores
$scores = array();
}
// add the new score to scores array
array_push($scores, $new_score);
// persist scores array as json content
file_put_contents($json_file, json_encode($scores));
?>
then in the ActionScript side, you can do :
function getProcessdata(e:Event) : void
{
var rawData:String = e.target.data;
var data:Array = JSON.parse(rawData) as Array;
for(var i:int = 0; i < data.length; i++){
trace(data[i].name); // gives for example : "Player1"
}
}
Hope that can help.

Sending and receiving data from Flash AS3 to PHP

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.

Load JSON data with URL loader

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;
?>

What am I doing wrong trying to get data with URLLoader?

Hey, I have a php document dynamicly generating the following:
peerID=e224d6cac76ef3181d4804858d82ebeee7e67ad7bdd7b02f3857a700b0ec7fbc
(from get_peerID.php)
I'm using the following AS3 to try and get this data:
private var myLoader:URLLoader = new URLLoader();
private function sendData():void {
writeText("sending data...");
var objSend:Object = new Object;
objSend.peerID = myID.text;
put_peerID.send( objSend );
writeText("http://localhost/example.com/scripts/get_peerID.php?peerID=" + myID.text);
var myRequest:URLRequest = new URLRequest("http://localhost/example.com/scripts/get_peerID.php?peerID=" + myID.text);
myRequest.contentType = "text/plain";
//var myLoader:URLLoader = new URLLoader();
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
configureListeners(myLoader); //.addEventListener(Event.COMPLETE,onComplete);
myLoader.load(myRequest);
}
private function configureListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
dispatcher.addEventListener(Event.OPEN, openHandler);
dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}
private function completeHandler(event:Event):void {
writeText("completeHandler: " + myLoader.data.peerID);
}
private function openHandler(event:Event):void {
writeText("openHandler: " + event);
}
private function progressHandler(event:ProgressEvent):void {
writeText("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
writeText("securityErrorHandler: " + event);
}
private function httpStatusHandler(event:HTTPStatusEvent):void {
writeText("httpStatusHandler: " + event);
}
private function ioErrorHandler(event:IOErrorEvent):void {
writeText("ioErrorHandler: " + event);
}
Which generates the following text (from writeText()):
sending data...
http://localhost/example.com/scripts/get_peerID.php?peerID=5131079b60ba3ae05f9d54568896db1e04f772f97bb98c6d525cb8ba3032798b
openHandler: [Event type="open" bubbles=false cancelable=false eventPhase=2]
httpStatusHandler: [HTTPStatusEvent type="httpStatus" bubbles=false cancelable=false eventPhase=2 status=200 responseURL=null]
So, its not giving me the data that I need. I'm not sure what to try next. I've been in and out of forums all day so any help would be appreciated.
It's not working because I was running it on my localhost. Adobe says:
For Flash Player 8 and later:
Data loading is not allowed if the
calling file is in the
local-with-file-system sandbox and
the target resource is from a network
sandbox.
Data loading is also not allowed if
the calling file is from a network
sandbox and the target resource is
local.
After released it and put it up online it work.

Categories