I'm trying to pull data into flash using JSON but i keep getting this error
JSONParseError: Unexpected < encountered
at com.adobe.serialization.json::JSONTokenizer/parseError()
at com.adobe.serialization.json::JSONTokenizer/getNextToken()
at com.adobe.serialization.json::JSONDecoder/nextToken()
at com.adobe.serialization.json::JSONDecoder()
at com.adobe.serialization.json::JSON$/decode()
at jsonairtest_fla::MainTimeline/decodeJSON()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
even though i can runt the pp file in the browser and the ouput looks fine to me, i even tried calling up a txt file and that worked but i don't know what am i doing wrong here.
Here is AS3 code
import com.adobe.serialization.json.JSON
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest();
request.url = "pull.php";
loader.load(request);
loader.addEventListener(Event.COMPLETE, decodeJSON);
function decodeJSON(event:Event):void{
var loader2:URLLoader = URLLoader(event.target);
//trace(event.target.data);
var People:Array = JSON.decode(loader2.data);
trace(People[0].NETWORKNAME) ;
trace(People[1].NETWORKNAME) ;
}
PHP code:
<?php
$host="localhost";
$user="";
$password="";
$database="db name";
$tablename="table name";
header('Content-type: application/json');
if(!$connection = mysql_connect($host,$user,$password))
{
//if connection not eastablished then display message and die
$message = mysql_error();
//echo "$message<br>";
die();
}else
// in case the connection is eastablished
$message = "Connection eastablished.....";
//echo"$message<br>";
mysql_select_db($database,$connection)
or die("database not found");
$query = mysql_query("SELECT NETWORKNAME from $tablename);
$returnArray = array();
while($row=mysql_fetch_assoc($query))
array_push($returnArray, $row);
mysql_close();
echo json_encode($returnArray);
?>
To convert the response into an array of undecoded JSON objects, try this:
var jsonArray:Array = loader2.data.match(/\{.*?\}/gi);
Then simply loop through calling JSON.decode on each member of the array. :)
In your php output, are you setting your header type to json?
header('Content-type: application/json');
Your decoder may need the type to be correct.
The error message says there's a < in an unexpected position.
My guess is that you are inadvertedly reading your php from the file system, instead of running it on a server. Your file is being not executed as php code and that < is probably the opening tag of your php script (<? or <?php).
If you are running this code from the IDE, your url should be something like:
htp://localhost/my_project/pull.php
If you run this on a browser, you don't need an absolute path, but make sure your swf runs on an http environment (which is able to execute php, of course). That is, test it like this:
http://localhost/my_project/index.php
(where index.php is the hmtl file that embeds your swf)
Related
When i tried to use var textField and String(), the result display null.What i posted below, it display Error #2007 Parameter text must be non-null. Trying to pass the echoed results from mysql through php on AS3, through a few dynamic text box.
But when i switch it to Trace(event.target.data), it shows the correct Data.
Here is my AS3 code
var Mend:URLRequest = new URLRequest("http://localhost/Autoresult.php");
Mend.method = URLRequestMethod.POST;
var variablesss:URLVariables = new URLVariables();
variablesss.nobed1 = result.text;
variablesss.LoZip=result2.text;
variabless.rangelow=result3.text;
Mend.data = variablesss;
var BLoader:URLLoader = new URLLoader();
BLoader.dataFormat = URLLoaderDataFormat.TEXT;
BLoader.addEventListener(Event.COMPLETE,Candler);
BLoader.load(Mend);
// handler for the PHP script completion and return of status
function Candler(event:Event){
var seVariables: URLVariables = new URLVariables(event.target.data);
result.text=seVariables.nobed1;
result2.text=seVariables.LoZip1;
result3.text=seVariables.rangelow1;
}
Here is my php code
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
session_start();
include 'connect.php';
$_SESSION['username'];
$username=$_SESSION['username'];
$result=mysqli_query($con,"SELECT * FROM Test WHERE username = '$username'")or die( mysqli_error($con));
$solutions = array();
$check_num_rows=mysqli_num_rows($result);
while ($row = mysqli_fetch_assoc($result))
{
$solutions[0]=$row['nobed1'];
$solutions[1]=$row['LoZip1'];
$solutions[2]=$row['rangelow1'];}
echo "nobed1=.$solutions[0]&LoZip1=.$solutions[1]&rangelow1=.$solutions[2]";
?>
Thanks for your time
without looking into it too deeply, it seems like it might be a type miss-match.
you could try
var seVariables: URLVariables = new URLVariables(event.target.data + "");
that way it is converted to text
I managed to resolve my problem, changing the php, and putting the result in a string, pass it through to AS3, then split up the answer and put them into the dynamic text box.
Here is my code.
function Candler(event:Event){
var fromPhp:String = event.target.data;
var errors:Array = fromPhp.split(",");
trace(errors.length)
result.text= (errors[0].replace(/^\s+|\s+$/mg, ""));
result2.text= (errors[1].replace(/^\s+|\s+$/mg, ""));
result3.text= (errors[2].replace(/^\s+|\s+$/mg, ""));
result4.text= (errors[3].replace(/^\s+|\s+$/mg, ""));
}
Really need another set of eyes on this, and thanks in advance! My php code:
<?php
header('Location: videorecord.html');
$hour = time() + 3600;
setcookie(UserName, $_POST['UserName'], $hour);
$_COOKIE["UserName"];
mysql_connect("localhost", "XXX", "XXX") or die(mysql_error());
mysql_select_db("XXX") or die(mysql_error());
$insert = "INSERT INTO usercards (RecName, Message, RecEmail, EventTitle)
VALUES
('$_POST[RecName]', '$_POST[Message]', '$_POST[RecEmail]', '$_POST[EventTitle]')";
$add_member = mysql_query($insert);
$var1="recpt=".$_POST['RecName'];
echo "&lVar1=$var1";
?>
Sending the variables via a AS2 script to a swf contained in the header file. The AS2 code:
lv = new LoadVars();
// define onLoad Callback
lv.onLoad = onLoadCallBack;
// send and load variables
lv.load("http://XXXXX.com/pages/process_card.php");
// onLoad Callback
function onLoadCallBack(success)
{
// if succes
if(success)
{
// trace variables
trace(this.lVar1);
_global.lVar1 = this.lVar1;
}
else
{
// loading failed
trace("Loading Error!!");
}
}
//end getting the external data
var movieName:String = lVar1;
End result keep getting undefined for the return.
I do php but this AS2 stuff is new to me (got the code thru google), little better at AS3.
Appreciate any suggestions, help, 2 days of looking for answers and I'm about done for.
Thanks
use the sendAndLoad method to post data from flash to PHP and to load the response.
var send_lv:LoadVars = new LoadVars();
var result_lv:LoadVars = new LoadVars();
result_lv.onLoad = function(success:Boolean):Void {
trace('result_lv.phpvar=' + result_lv.phpvar);
}
send_lv.flashvar = 'Hello from flash';
send_lv.sendAndLoad('path/to/file.php',result_lv, 'POST');
file.php
<?php
$fashvar = $_POST['flashvar'];
echo '&phpvar=Hello from PHP&';
?>
Output in flash console :
Hello from PHP
I got two php pages:
client.php and server.php
server.php is on my web server and what it does is open my amazon product page and get price data and serialize it and return it to client.php.
Now the problem I have is that server.php is getting the data, but when I return it and do echo after using unserialize(), it shows nothing. But if I do echo in server.php, it shows me all the data.
Why is this happening? Can anyone help me please?
This the code I have used:
client.php
$url = "http://www.myurl.com/iec/Server.php?asin=$asin&platform=$platform_variant";
$azn_data = file_get_contents($url);
$azn_data = unserialize($azn_data);
echo "\nReturned Data = $azn_data\n";
server.php
if(isset($_GET["asin"]))
{
$asin = $_GET["asin"];
$platform = $_GET["platform"];
echo "\nASIN = $asin\nPlatform = $platform";
//Below line gets all serialize price data for my product
$serialized_data = amazon_data_chooser($asin, $platform);
return($serialized_data);
}
else
{
echo "Warning: No Data Found!";
}
On server.php , you need to replace your following line:
return($serialized_data);
for this one:
echo $serialized_data;
because client.php reads the output of server.php, return is used to pass information from functions to caller code.
UPDATE:
Apart from the fixes above, you're hitting a bug in unserialize() function that presents with some special combination of characters, which your data seems to have, the solution is to workaround the bug by base64() encoding the data prior to passing it to serialize() , like this:
In client.php:
$azn_data = unserialize(base64_decode($azn_data));
In server.php:
echo base64_encode($serialized_data);
Source for this fix here .
You are not serializing your data on server side so there is nothing to deserialize on client side.
return(serialize($serialized_data));
Edit:
if(isset($_GET["asin"]))
{
$asin = $_GET["asin"];
$platform = $_GET["platform"];
echo "\nASIN = $asin\nPlatform = $platform";
//Below line gets all serialize price data for my product
$serialized_data = amazon_data_chooser($asin, $platform);
die(serialize($serialized_data));
}
else
{
echo "Warning: No Data Found!";
}
The code below calls a PHP file for a true or false text result using the dojo.xhrGet method. When I load the PHP file by itself (replacing the $variable = $_GET("passedVariable"); with a hard-wired value), it correctly generates a "true" or "false" in my browser window. However, when I run the call in my larger web app, it returns the PHP source code instead of the results of my database query. Using JQuery's .get() method, I receive a XML object.
Here's the Javascript...
dojo.xhrGet({
url: "php/check.php",
handleAs: "text",
content: {guid: featureGuid},
load: function(response){
alert(response);
dojo.style(dojo.byId("photoLink"), "display", "");
}
});
Here's the PHP...
<?php
$guid = $_GET["guid"];
// Connect to Database
$server = "server";
$connectionSettings = array("Database"=>"db", "UID"=>"uid", "PWD"=>"pwd");
$connection = sqlsrv_connect($server, $connectionSettings);
if (!$connection){
die("Failed Connection");
}
// Prepare and Execute query
$sql = "sql";
$results = sqlsrv_query($connection, $sql);
if ($results){
$rows = sqlsrv_has_rows( $results );
if ($rows === true) {
header('Content-Type: text/plain');
echo "true";
}
else {
header('Content-Type: text/plain');
echo "false";
}
}
else{
header('Content-Type: text/plain');
echo "false";
}?>
Anything anybody see wrong with this?
Thanks.
I'd check the requests and responses using Firebug - check that the URLs and headers are the same when you call the URL directly from the browser as opposed to via the XHR.
I am not sure but:
Try making sure that your Main App is executing PHP properly, it seems odd that JavaScript can pull the source code.
Try adding: die() after echo true or echo false which will prevent it from going any further.
The reason I say to check the larger app for PHP execution is because it almost seems like the webserver is rendering the source code as html and not running it through the interpreter.
i am having strange issue with Flash and PHP. actually i have one Forgot password form in flash in which user enters his email id and when presses submit button flash passes data to PHP and retrieves(here i am stuck) data from PHP.
The issue is Flash getting UNDEFINED from PHP.
my flash code.
var email_id:RegExp = /(\w|[_.\-])+#((\w|-)+\.)+\w{2,4}+/;
var urlRequest:URLRequest = new URLRequest("forgot_password.php");
var urlVariable:URLVariables = new URLVariables();
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete);
btn_submit.addEventListener(MouseEvent.CLICK, btn_submit_click);
function btn_submit_click(e:Event)
{
if(txt_email.text == "")
{
txt_error.text = "Email can not be blank.";
}
else if(!email_id.test(txt_email.text))
{
txt_error.text = "Enter proper email address.";
}
else
{
urlVariable.mailId = txt_email.text;
urlRequest.data = urlVariable;
urlLoader.load(urlRequest);
}
}
function urlLoader_complete(e:Event)
{
trace(e.target.data.return_var); // **it receive Undefined** i am checking in flashlog.txt :(
//txt_error.text = e.target.data.return_var;
}
my PHP code
<?php
require_once('connection.php');
$query = "select * from user_account where email='".$_REQUEST['mailId']."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
echo "return_var=success";
}
else
{
echo "return_var=failed";
}
?>
there is a space before return_var but i don't know why.. i have checked my PHP file 100 times it is perfect than what is the issue??????????????????????????????????????????
EDIT:
If i am tracing
trace(e.target.data);
it traces
%20return%5Fvar=success
Note %20 before return%5var // what is that?????????????
Obviously problem isn't in PHP, anyway you should write it something like this to prevent SQL injection...
<?php
require_once 'connection.php';
$email = $_GET['mailId'];
$email = mysql_real_escape_string($email);
$query = "SELECT email FROM user_account WHERE email = '$email' LIMIT 1";
$result = mysql_query($query);
echo (mysql_num_rows($result) > 0)? 'return_var=success': 'return_var=failed';
?>
Remove this line:
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
and change your urlLoader_complete() function to:
function urlLoader_complete(e:Event)
{
var loader:URLLoader = URLLoader(e.target);
var vars:URLVariables = new URLVariables(loader.data);
trace(vars.return_var);
}
does that help?
First of all thank you all for your contributions.
Now the issue was not related with Flash or PHP but it was related with our server. if i am creating PHP file and directly saving on our server than that PHP file gives response with adding one space before variable name. and if i am creating PHP file and saving it in my local drive and than pasting it on my server it works perfectly!!!!!!!!!!!!!!!!!
see the response difference between two files..............
return_var=success
return_var=success // adding space before response.
may be its issue related with memory but now its working fine so cheers!!!!!!!!!
Again many Thanx.