As3 + PHP error - php

Im gettin this error using as3 votingpoll.
I dont understand what is wrong, since i only know basic coding.
I really would need to get this working for a school project.
Hope any one can help me out !
Thanks alot
TypeError: Error #2007: Parameter text must be non-null.
at flash.text::TextField/set text()
at Onlinepoll_fla::WholePoll_1/completeHandler()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
AS3 code request:
stop(); // Stop the timeline since it does not need to travel for this to run
// Assign a variable name for our URLVariables object
var variables1: URLVariables = new URLVariables();
// Build the varSend variable
var varSend1: URLRequest = new URLRequest("parse_my_poll.php");
varSend1.method = URLRequestMethod.POST;
varSend1.data = variables1;
// Build the varLoader variable
var varLoader1: URLLoader = new URLLoader;
varLoader1.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader1.addEventListener(Event.COMPLETE, completeHandler1);
// Set variable to send to PHP here for the varloader below
variables1.myRequest = "load_numbers";
// Send data to php file now, and wait for response using the COMPLETE event
varLoader1.load(varSend1);
function completeHandler1(event: Event): void {
count1_txt.text = "" + event.target.data.choice1Count;
count2_txt.text = "" + event.target.data.choice2Count;
count3_txt.text = "" + event.target.data.choice3Count;
}
**as3 Send code**
// hide the little processing movieclip
processing_mc.visible = false;
// Initialize the choiceNum variable that we will use below
var choiceNum:Number = 0;
// Set text formatting colors for errors and success messages
var errorsFormat:TextFormat = new TextFormat();
errorsFormat.color = 0xFF0000; // bright red
var successFormat:TextFormat = new TextFormat();
successFormat.color = 0x00FF00; // bright green
/////////////////////////////////////////////////////////////
// Button Click Functions
function btn1Click(event:MouseEvent):void{
choiceNum = 1;
choice_txt.text = choice1_txt.text;
}
function btn2Click(event:MouseEvent):void{
choiceNum = 2;
choice_txt.text = choice2_txt.text;
}
function btn3Click(event:MouseEvent):void{
choiceNum = 3;
choice_txt.text = choice3_txt.text;
}
// Button Click Listeners
btn1.addEventListener(MouseEvent.CLICK, btn1Click);
btn2.addEventListener(MouseEvent.CLICK, btn2Click);
btn3.addEventListener(MouseEvent.CLICK, btn3Click);
//////////////////////////////////////////////////////////////
// Assign a variable name for our URLVariables object
var variables:URLVariables = new URLVariables();
// Build the varSend variable
var varSend:URLRequest = new URLRequest("parse_my_poll.php");
varSend.method = URLRequestMethod.POST;
varSend.data = variables;
// Build the varLoader variable
var varLoader:URLLoader = new URLLoader;
varLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader.addEventListener(Event.COMPLETE, completeHandler);
// Handler for PHP script completion and return
function completeHandler(event:Event):void{
// remove processing movieclip
processing_mc.visible = false;
// Clear the form fields
choice_txt.text = choice1_txt.text;
choiceNum = 0;
// Load the response from the PHP file
status_txt.text = event.target.data.return_msg;
status_txt.setTextFormat(errorsFormat);
if (event.target.data.return_msg == "Thanks for voting!") {
// Reload new values into the count texts only if we get a proper response and new values
status_txt.setTextFormat(successFormat);
count1_txt.text = "" + event.target.data.choice1Count;
count2_txt.text = "" + event.target.data.choice2Count;
count3_txt.text = "" + event.target.data.choice3Count;
}
}
// Add an event listener for the submit button and what function to run
vote_btn.addEventListener(MouseEvent.CLICK, ValidateAndSend);
// Validate form fields and send the variables when submit button is clicked
function ValidateAndSend(event:MouseEvent):void {
//validate form fields
if(!choice_txt.length) {
// if they forgot to choose before pressing the vote button
status_txt.text = "Please choose before you press vote.";
status_txt.setTextFormat(errorsFormat);
} else {
status_txt.text = "Sending...";
processing_mc.visible = true;
// Ready the variables for sending
variables.userChoice = choiceNum;
variables.myRequest = "store_choice";
// Send the data to the php file
varLoader.load(varSend);
} // close else after form validation
} // Close ValidateAndSend function ////////////////////////
PHP code:
<?php
/*
::::::::::Script Written By: Adam Khoury # www.developphp.com:::::::::::::
:::::::::If you find www.developphp.com tutorials helpful or handy:::::::::::::
:::::::::::please link to it wherever possible to help others find it::::::::::::::::
*/
// ---------------------------------------- Section 1 -----------------------------------------------
// IMPORTANT!!!! Connect to MySQL database here(put your connection data here)
mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db("data") or die (mysql_error());
// When Flash requests the totals initially we run this code
if ($_POST['myRequest'] == "load_numbers") {
// Query the totals from the database
$sql1 = mysql_query("SELECT id FROM votingPoll WHERE choice='1'");
$choice1Count = mysql_num_rows($sql1);
$sql2 = mysql_query("SELECT id FROM votingPoll WHERE choice='2'");
$choice2Count = mysql_num_rows($sql2);
$sql3 = mysql_query("SELECT id FROM votingPoll WHERE choice='3'");
$choice3Count = mysql_num_rows($sql3);
echo "choice1Count=$choice1Count";
echo "&choice2Count=$choice2Count";
echo "&choice3Count=$choice3Count";
}
// ---------------------------------------- Section 2 -----------------------------------------------
// IF POSTING A USER'S CHOICE
if ($_POST['myRequest'] == "store_choice") {
//Obtain user IP address
$ip = $_SERVER['REMOTE_ADDR'];
// Create local variable from the Flash ActionScript posted variable
$userChoice = $_POST['userChoice'];
$sql = mysql_query("SELECT id FROM votingPoll WHERE ipaddress='$ip'");
$rowCount = mysql_num_rows($sql);
if ($rowCount == 1) {
$my_msg = "You have already voted in this poll.";
print "return_msg=$my_msg";
} else {
$sql_insert = mysql_query("INSERT INTO votingPoll (choice, ipaddress) VALUES('$userChoice','$ip')") or die (mysql_error());
$sql1 = mysql_query("SELECT * FROM votingPoll WHERE choice='1'");
$choice1Count = mysql_num_rows($sql1);
$sql2 = mysql_query("SELECT * FROM votingPoll WHERE choice='2'");
$choice2Count = mysql_num_rows($sql2);
$sql3 = mysql_query("SELECT * FROM votingPoll WHERE choice='3'");
$choice3Count = mysql_num_rows($sql3);
$my_msg = "Thanks for voting!";
echo "return_msg=$my_msg";
echo "&choice1Count=$choice1Count";
echo "&choice2Count=$choice2Count";
echo "&choice3Count=$choice3Count";
}
}
?>

Apparently, your event.target.data.return_msg or event.target.data.choice1Count etc variables are empty (null).
First check if your PHP script is echoing a correct response ($my_msg or $choice1Count might be null there as well). If the PHP script is fine, try to trace these values in your completeHandler method:
trace("message : " + event.target.data.return_msg);
trace("choice1Count : " + event.target.data.choice1Count);

Related

How to pass variables from PHP to Flash (ActionScript 3)

I need to select game's number from MySql database and pass It to Flash game (ActionScript 3).
For now I have AS3 code:
function getVars(e:Event):void{
var req:URLRequest = new URLRequest("top.php");
var loader:URLLoader = new URLLoader(req);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, getVarComplete);
}
function getVarComplete(e:Event):void{
var gameNr.text = e.target.data;
}
And here is PHP code (I don't know how selected row pass to variable and send It to flash)
$id = $_SESSION['id'];
$mysqli = new mysqli("localhost","xxx","xxx","xxx");
$query = "SELECT GameNr
FROM Game
WHERE FBId = '". mysql_real_escape_string($id) ."'
ORDER BY PlayTime DESC LIMIT 1";
UPDATE:
If I use following PHP:
<?php
session_start();
$id = $_SESSION['id'];
$mysqli = new mysqli("localhost","xx","xx","xx");
$query = "SELECT GameNr
FROM Game
WHERE FBId = '". mysql_real_escape_string($id) ."'
ORDER BY PlayTime DESC LIMIT 1";
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
}
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row["GameNr"];
}
$result->free();
}
$mysqli->close();
?>
www.myhost.com/top.php returning correct value NA==
If I use following AS3 code:
function onVarsLoaded(e:Event) {
var msg:String = "Communication with the server was successful.\n\n";
msg += "foo -> "+e.target.vars.foo+"\n";
trace(msg);
}
It returning me: foo -> undefined
If I change this
msg += "foo -> "+e.target.vars.foo+"\n"; to
msg += "foo -> "+e.target.vars+"\n";
It returning me incorrect value: foo -> NA=%3D
Try this:
AS3:
import net.kaegi.loaders.VarLoader;
var vl:VarLoader;
sendBtn.addEventListener(MouseEvent.CLICK,sendBtnHandler);
function sendBtnHandler(e:MouseEvent) {
// Variables sent by POST-Method:
var varObj:Object = {};
varObj.textinput0 = escape(textinput0.text);
varObj.textinput1 = escape(textinput1.text);
vl = new VarLoader("http://yourserver.com/landing.php?foo=foo", varObj);
vl.addEventListener(Event.COMPLETE, onVarsLoaded);
vl.addEventListener(Event.CANCEL, onVarsCancel);
}
function onVarsLoaded(e:Event) {
var msg:String = "Communication with the server was successful.\n\n";
msg += "foo -> "+e.target.vars.foo+"\n";
tf_servermsg.textColor = 0x009900;
tf_servermsg.text = msg;
}
function onVarsCancel(e:Event) {
tf_servermsg.textColor = 0x990000;
tf_servermsg.text = e.target.errormsg;
}
PHP
// handle coming get
$foo = $_GET["foo"];
// handle coming post from flash
$textinput0 = $_POST["textinput0"];
$textinput1 = $_POST["textinput1"];
// send it to flash
$yourdata = "hello world"; // your mysql data here
echo $yourdata;
PHP code in addition to your code
$mysqli->real_query($query);
$res = $mysqli->use_result();
while ($row = $res->fetch_assoc()) {
echo $row['GameNr'];
}
Please check in format the data is required from PHP script. currently the php code will give you result of GameNr as text.
Hope it helps!

retieve data from database using as3

I had created a database "new" using xampp localhost database had 2 tables user and score. I had an AS3 code which had 2 input textfield to insert user and score value into database tables.
Now I am trying to retrieve the inserted scores from database using user name. I have taken another text field to take user name and a button when I write "sarah" and click button it will return the score of sarah which is already inserted in database. But code is showing an error. I tried a lot but can not fix it.please help.here is my code
AS3 code:
btn2.addEventListener(MouseEvent.MOUSE_DOWN, fetchscore);
function fetchscore(event:MouseEvent)
{
var phpVars:URLVariables = new URLVariables();
var phpFileRequest:URLRequest = new URLRequest('http://localhost/collectscore.php');
phpFileRequest.method = URLRequestMethod.POST;
var phpLoader:URLLoader = new URLLoader();
phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
phpLoader.addEventListener(Event.COMPLETE, showResult);
phpVars.systemCall = "processLogin";
phpVars.cname = Name.text;
phpLoader.load(phpFileRequest);
}
function showResult(e:Event)
{
//trace(phpVars.result);
result_text.text = "" + e.target.data.systemResult;
}
fetchscore.php
<?php
include('connect.php');
$username = $_POST['cname'];
if ($_POST['systemCall'] == "processLogin"){
$sqlqry = "SELECT * FROM scoreu WHERE username='$username'";//scoreu is my DBtable with two field user and score
$query = mysqli_query($sqlqry);
$login_counter = mysqli_num_rows($query);
if ($login_counter > 0) {
while ($data = mysqli_fetch_array($query)) {
if (mysqli_query($link), "SELECT score FROM scoreu WHERE user='$username'")) {
$findscore = $data['score'];
print 'result=$findscore';
}
}
} else {
print 'result=The login details dont match names.';
}
}
?>
connect.php
<?php
// connect.php
$db_name = 'new';
$db_username = 'root';
$db_password = '';
$db_host = 'localhost';
$link = mysqli_connect($db_host, $db_username, $db_password, $db_name);
if (mysqli_connect_errno()) {
die('Failed to connect to the server : '.mysqli_connect_error());
}
?>
You have some "problems" in your code, lets start by the PHP code.
PHP code :
<?php
// collectscore.php
include('connect.php');
$username = $_POST['cname'];
if ($_POST['systemCall'] == "processLogin"){
// you need only one request to get the score
$query = mysqli_query($link, "SELECT score FROM scoreu WHERE user = '$username'");
// you have to fetch the result into a php var
if ($data = mysqli_fetch_assoc($query)) {
$findscore = $data['score'];
// you should use double quotes when passing vars into a string
// otherwise, if you want use single quotes, you can write it : print 'result='.$findscore;
print "result=$findscore";
} else {
print 'result=The login details dont match names.';
}
}
?>
ActionScript code :
function fetchscore(event:MouseEvent): void
{
var phpVars:URLVariables = new URLVariables();
phpVars.systemCall = "processLogin";
phpVars.cname = cname.text; // name text field
var phpFileRequest:URLRequest = new URLRequest('http://127.0.0.1/collectscore.php');
phpFileRequest.method = URLRequestMethod.POST;
// you forgot to send your POST vars, for that, we use URLRequest.data
phpFileRequest.data = phpVars;
var phpLoader:URLLoader = new URLLoader();
phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
phpLoader.addEventListener(Event.COMPLETE, showResult);
phpLoader.load(phpFileRequest);
}
function showResult(e:Event):void
{
// here the var should be the same as in the PHP script, result in this case : print "result=$findscore";
trace(e.target.data.result);
}
Hope that can help.

Flash AS3 Error #2101 for login screen

i'm still novice in AS3 Programming i was trying to get a login screen to work on my AIR Application, but i got error #2101 The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
here's the code for processLogin
public function processLogin():void {
if(username.text != "" && password.text != "")
{
var checkName = username.text
var checkPass = password.text
var resulttext = result_text.text
var request:URLRequest = new URLRequest("http://localhost/caservers/aksessistemlogin.php")
var loader:URLLoader = new URLLoader()
var variables:URLVariables = new URLVariables()
variables.username = checkName
variables.password = checkPass
variables.systemResult = resulttext
loader.dataFormat = URLLoaderDataFormat.VARIABLES
request.data = variables
request.method = URLRequestMethod.POST
loader.addEventListener(Event.COMPLETE, logincheck)
loader.load(request)
}
function logincheck (event:Event):void {
if (username.text == checkName && password.text == checkPass){
gotoAndPlay(2);
}else{
result_text.text = resulttext ;
}
}
}
and this one is the code for PHP
<?php
include_once "connect.php";
$username = $_POST['username'];
$password = $_POST['password'];
if ($_POST['systemCall'] == "checkLogin") {
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$query = mysqli_query($sql);
$login_counter = mysqli_num_rows($query);
if ($login_counter > 0) {
while ($data = mysqli_fetch_array($query)) {
}
} else {
$systemResult = "The login details don't match our records";
}
}
?>
what i'm intend to do is to check if the username and password is match with the one in the database, i followed some tutorials but it ended up advancing to next frame even without typing anything in the text input (just by clicking submit).
any help will be very very appreciated! thanks in advance..
When you have this line in AS3:
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
You are telling flash to decode the response from the loader as URL encoded variables. Your response however must not be that, because you get an error when it tries to decode the output of your PHP page as URL variables.
Flash will automatically know that you are sending URL encoded data when you assign a URLVariables object to the data property.

Trouoble with Ajax submitting to database

I have this form:
<form method = \"get\" action = \"\" onsubmit = \"return addBeer('$user','$id','$name','$abv','$ibu','$icon','$style','$brewery','$breweryID','$icon')\" >
<p> <input type = \"submit\" value = \"Go Fishing\" /> </p>
</form>
which calls this JavaScript function:
function addBeer(user,id,bname,abv,ibu,icon,bstyle,brewery,breweryID,icon)
{
//get elements
alert('userID' + user);
alert('beerid'+id);
alert('beername'+bname);
alert('style'+bstyle);
alert('brewery'+brewery);
alert('abv'+abv);
alert('ibu'+ibu);
alert('brewery id'+ breweryID);
alert('icon'+icon);
//run ajax
var ajaxSettings2 =
{
type: "POST",
url: "addBeer.php",
data: "uID="+user+"&bID="+id+"&bName="+bname+"&bStyle="+bstyle+"&bBrewery="+brewery+"&abv="+abv+"&ibu="+ibu+"&breweryID="+breweryID,
success: function()
{
$('#sbutton').remove();
alert('Load was performed.');
},
error: function(xhr, status, error) { alert("error: " + error); } };
$.ajax(ajaxSettings2);
}
All the alerts work so I know for a fact that the information is getting passed fom the form to the function, but it fails on the ajax call to addBeer.php because it runs the error function and pop up the error alert. Unfortunetley nothing is reported in the pop up.
This is the addBeer.php file that is called to add to the database:
<?php
require_once('myConnectDB.inc.php');
require_once('page.inc.php');
session_start();
//add beer to database code
$userID = $_POST['uID'];
$beerName = $_POST['bName'];
$beerID = $_POST['bid'];
$brewery = $_POST['bBrewery'];
$style = $_POST['bStyle'];
$abv = $_POST['abv'];
$ibu = $_POST['ibu'];
$breweryID = $_POST['breweryID'];
//$icon = $_POST['icon'];
//get brewery icon
$uri3 = "http://api.brewerydb.com/v2/brewery/$breweryID?key=myKey&format=json";
$response3 = file_get_contents($uri3);
//parse xml
$myBrew = json_decode($response3);
$iconBrew = $myBrew->data->images->medium;
//add above data to database
$db = new myConnectDB();
$beerName = $db->real_escape_string($beerName);
$beerID = $db->real_escape_string($beerID);
$brewery = $db->real_escape_string($brewery);
$style = $db->real_escape_string($style);
$userID = $db->real_escape_string($userID);
$abv = $db->real_escape_string($abv);
$ibu = $db->real_escape_string($ibu);
$breweryID = $db->real_escape_string($breweryID);
$icon = $db->real_escape_string($icon);
$query3 = "INSERT INTO tableName (userID,beerID,beerName,beerStyle,beerBrewery,abv,ibu,breweryID,icon, brewIcon) VALUES ($userID, '$beerID', '$beerName', '$style' , '$brewery', '$abv','$ibu','$breweryID', '$icon', '$iconBrew')";
$db->query($query3);
?>
I took out my api key and table name for security.
I have checked the network tab in chrome under inspect element and when I click on addBeer.php call and look under headers it shows in form data that the information is being passed.
Update:
I am escaping my quotes because its being printed from php
After lots and lots of frustration, I figured out my problem. The information I was sending, I was querying from another database and all that info was not always complete.
If I clicked submit and it and one of the variables in the function call was an empty string it did not like it.
You have your method as GET in the form but POST in your Ajax.

How do I get javascript to read the output of a php file

First off hello, I am new here.
My problem is that I have a php file pulling info from a database. I will post the code below.
What I need is for my JavaScript to take the output and load it into a list that generates some flash cards.
code sample `$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
$query1 = "SELECT * FROM category_tb WHERE cat_name = '$category'";
$result1 = mysql_query($query1) or die ("Error in query: $query1. " . mysql_error());
while ($row = mysql_fetch_array($result1))
{
$cat_num = $row[1];
}
// This establishes a link to MySQL
$query = "SELECT * FROM english_lang, finnish_lang ".
"WHERE english_lang.lang_id = finnish_lang.lang_id AND english_lang.cat_id = $cat_num";
$rt = mysql_query($query) or die ("Error in query: $query. " . mysql_error());
while($nt=mysql_fetch_array($rt)){
echo "{\"english\": \"$nt[1]\", \"finnish\": \"$nt[6]\" , \"asked\": states.notAsked},";
}
`
So this basicly gets some data and formats it to be used by the javascript.
if you want to look at the output of this to get a better idea the go here
http://languagelearner.byethost2.com/vocabulary2.php
select 1 of the first 2 categories as they are the only ones with data right
now.
the javascript is this:
code sample `
var string1;
var string2;
var number;
var states = {"oneVisible": 0, "bothVisible": 1, "notAsked": 2, "asked": 3}
var state = states.bothVisible;
var numberOfWordsAsked = 0;
var words = {"list": [
]
}
function displayWords(){
if (state == states.bothVisible) {
if (numberOfWordsAsked < words.list.length) {
state = states.oneVisible;
number = Math.floor(Math.random() * words.list.length);
while (words.list[number].asked == states.asked) {
number = Math.floor(Math.random() * words.list.length);
}
string1 = words.list[number].english;
string2 = words.list[number].finnish;
document.getElementById("fin").style.display = 'none';
document.getElementById("eng").innerHTML = words.list[number].english;
document.getElementById("fin").innerHTML = words.list[number].finnish;
document.getElementById("b").value = "Show word";
document.getElementById("correct").style.display = 'none';
}
else {
document.getElementById("eng").innerHTML = "You know all the words in this category, congratulations!";
document.getElementById("fin").style.display = 'none';
document.getElementById("b").style.display = 'none';
document.getElementById("correct").style.display = 'none';
}
}
else {
document.getElementById("fin").style.display = 'inline';
state = states.bothVisible;
document.getElementById("b").value = "Wrong";
document.getElementById("correct").style.display = 'inline';
}
}
function setCorrect(){
words.list[number].asked = states.asked;
numberOfWordsAsked += 1;
displayWords();
}
//-->
</script>
`
so the output needs to go in here.
var words = {"list": [
]
Any help would be appreciated. I did not write the javascript, a friend did.
He used static info in the list.
Try AJAX. Check out http://www.w3schools.com/PHP/php_ajax_database.asp
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
alert(ajax.responseText);
}
};
ajax.open("GET", "ajax.php", true);
ajax.send(null);
outputs "hello world" when used in the same directory as a php file ajax.php:
<php
echo 'hello Word!';
?>
To put php data structures into something javascript can parse, use json_encode. That should be enough to help you on your way.

Categories