Load JSON data with URL loader - php

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

Related

Actionscripts3 read JSON from VPS issue

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.

Pass string from php to flash

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());
}

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.

How do I integrate Flash with 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"];
?>

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