Actionscripts3 read JSON from VPS issue - php

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.

Related

Actionscript3 SecurityError #2048

I have a problem with loading data from my PHP server. I can access it simply by link but in actionscript when I'm trying to load it just like in this thread: Get and parse JSON in Actionscript it is not working.
It just throws an event
[SecurityErrorEvent type="securityError" bubbles=false
cancelable=false eventPhase=2 text="Error #2048"].
What should I do? I've read something about cross-domain-policy so I have added file crossdomain.xml to PHP server like this:
<cross-domain-policy>
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="*"/>
<allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>
I tried adding this file almost everywhere. Can I do something more?
Code responsible for loading this data:
private function getURL():void
{
var request:URLRequest=new URLRequest("http://Journey.pe.hu/Journey/Users/");
ExternalInterface.call("console.log", request.url);
request.requestHeaders=[new URLRequestHeader("Content-Type", "application/json")];
request.method=URLRequestMethod.GET;
var loader:URLLoader=new URLLoader();
loader.addEventListener(Event.COMPLETE, receive);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, notAllowed);
loader.addEventListener(IOErrorEvent.IO_ERROR, notFound);
loader.load(request);
ExternalInterface.call("console.log", "l1");
}
protected function notAllowed(event:SecurityErrorEvent):void
{
ExternalInterface.call("console.log", event.toString());
}
protected function notFound(event:IOErrorEvent):void
{
ExternalInterface.call("console.log", "NOT FOUND");
}
protected function receive(event:Event):void
{
ExternalInterface.call("console.log", "Nameldasodoad");
var loader:URLLoader = URLLoader(event.target);
var jsonArray:Array = com.adobe.serialization.json.JSON.decode(loader.data);
//ExternalInterface.call("console.log", "Name " + jsonArray[0].Name);
//var jsonArray:Array = com.adobe.serialization.JSON.decode(loader.data);
}
Where did you add crossdomain.xml?
Basically, it should add at root directory.
In this case
http://journey.pe.hu/crossdomain.xml
By default, flash loads crossdomain.xml from root automatically.
If you can't add there, add here
http://Journey.pe.hu/Journey/crossdomain.xml
and load manually.
private function getURL():void
{
// load crossdomain.xml manually.
Security.loadPolicyFile("http://Journey.pe.hu/Journey/crossdomain.xml");
var request:URLRequest=new URLRequest("http://Journey.pe.hu/Journey/Users/");
ExternalInterface.call("console.log", request.url);
request.requestHeaders=[new URLRequestHeader("Content-Type", "application/json")];
request.method=URLRequestMethod.GET;
var loader:URLLoader=new URLLoader();
loader.addEventListener(Event.COMPLETE, receive);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, notAllowed);
loader.addEventListener(IOErrorEvent.IO_ERROR, notFound);
loader.load(request);
ExternalInterface.call("console.log", "l1");
}

Loading files with extension data from POST send - php as3

I'm trying to work out from an old as2 tutorial how to amend a script for as3/php eCard system for a business card but I can't find reference anywhere to how you'd do the following :
AS2 :
loadVariablesNum ("http://www.theSite.com/Cards/bCard/"+BcardText+".txt", 0);
AS3 :
// setup URLLoader
var loader:URLLoader = new URLLoader;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
// event listener for function when loaded
loader.addEventListener(Event.COMPLETE, varsLoaded);
// file URLRequest
loader.load(new URLRequest("http://www.theSite.com/Cards/bCard/"+BcardText+".txt"));
// set the variables from the data.txt file
function varsLoaded (event:Event):void {
//Load Data
cName.text = loader.data.cName;
cDescription.text = loader.data.cDescription;
}
With this it kicks out the following error message :
Error opening URL 'http://www.theSite.com/Cards/bCard/undefined.txt'
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
at Error$/throwError()
at flash.net::URLVariables/decode()
at flash.net::URLVariables()
at flash.net::URLLoader/onComplete()
I can't work out where or how you define the +BcardText+ for it to pull it in.
Any help would be gratefully received.
I'm not sure If I'm even close as its from as2, it seems the logical approach for loading it but I've not dealt with external files having parameters before.
Thanks in advance if anyone can help out in anyway!
NEW LOADER - FIXED!!!
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("http://www.theSite.com/Cards/bCard/"+BcardText+".txt");
loader.load(request);
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, loaderIOErrorHandler);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
function loaderIOErrorHandler(event:IOErrorEvent):void{
trace("ioErrorHandler: " + event);
}
// set the variables from the .txt file
function completeHandler (event:Event):void {
//trace("Content: " + loader.data);
this.Variable1.text = loader.data.Variable1; //Whatever dataField1 you saved as
this.Variable2.text = loader.data.Variable2; //Whatever dataField2 you saved as
}
Then you just setup FlashVars to distinguish the +BcardText variable in the loader prior to committing it!
BcardText was a variable defined in the as2 project. Look around (maybe on previous frames?) and you should find where it got declared. It looks like an ID to represent the card. So each card has a unique file 12345.txt, 09876.txt etc.
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("http://www.theSite.com/Cards/bCard/"+BcardText+".txt");
loader.load(request);
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, loaderIOErrorHandler);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
function loaderIOErrorHandler(event:IOErrorEvent):void{
trace("ioErrorHandler: " + event);
}
// set the variables from the .txt file
function completeHandler (event:Event):void {
//trace("Content: " + loader.data);
this.Variable1.text = loader.data.Variable1; //Whatever dataField1 you saved as
this.Variable2.text = loader.data.Variable2; //Whatever dataField2 you saved as
}
Then you just setup FlashVars to distinguish the +BcardText variable in the loader prior to committing it!
Have scoured the Internet and gone half mad working this out but finally chuffed to say I broke it's back...!
A big thanks for helping point me in the right direction guys. #Jason #Eugen
Θ)

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

Passing Variables from Flash to PHP

Creating a flash project where users can visit the site, and turn off/on objects in a house (ie. lights, tv, computer, etc.) The next user who will visit the house in the website, will see what lights or house appliances were left on. Flash variables are passed to PHP, and those variables are saved in an XML file. (For testing to see what is being saved to the XML file, on each click --vars.xml opens.) In the vars.xml file, I see that the house objects that were last turned on--are saved in the XML file--BUT in the SWF file, ONLY one of the objects that are listed in the XML are turned ON. Only the last object that was clicked on would show ON--not all the objects in the XML file.)
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.text.*;
import flash.net.*;
public class House extends MovieClip {
var request:URLRequest = new URLRequest("vars.xml")
var loader:URLLoader = new URLLoader();
// Constructor--------------------------------------------------------------------
public function House()
{
loader.addEventListener(Event.COMPLETE, parseXML);
loader.load(request);
}
// function sendPhp ------------------------------------------------------------------
function sendPhp():void
{
// send vars to php
var request:URLRequest = new URLRequest("write_xml.php"); // the php file to send data to
var variables:URLVariables = new URLVariables(); // create an array of POST vars
for (var i:int=0; i<onList.length; i++) {
variables["v"+i] = onList[i];
}
//variables['powerUsage'] = totalTxt.text;
request.data = variables; // send the vars to the data property of the requested url (our php file)
request.method = URLRequestMethod.POST; // use POST as the send method
try
{
var sender:URLLoader = new URLLoader();
sender.load(request); // load the php file and send it the variable data
navigateToURL(new URLRequest("vars.xml"), '_blank'); //show me the xml
}
catch (e:Error)
{
trace(e); // trace error if there is a problem
}
}
// function parseXML ------------------------------------------------------------------
function parseXML(evt:Event)
{
var xdata:XML = new XML(loader.data); // using E4x
//xdata.child(0);
for (var j:int=0; j<xdata.length(); j++) {
onList[j] = xdata.child(j);
for (var k:int=0; k<HouseObjects.length;k++) {
//root[onList[j]].gotoAndStop(3);
if (onList[j] == HouseObjects[k].name) {
HouseObjects[k].gotoAndStop(3);
//trace("tracing house objects"+ HouseObjects[k]);
trace("onList[j]: " + onList[j]);
trace("Array onList: " + onList);
}
}
}
}
} //end of class
} // end of package
You actually don't need to put all this code here, and it's true that you should make your app more secure , especially after showing all this info! If your XML is not the problem , check the Actionscript part, particularly the parseXML() function.
Are you able to trace the names of the components that are switched on? If yes , concentrate on what's happening in your loop. If your xml is fine, the problem is not passing data from PHP to Flash.
I like the tree house! ;)

Categories