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!
Related
I am trying to make a ajax call to do a database update in my php class. However, it seems the class is being called but the parameters are not passed for some reason.
Here is my jquery:
$(".sendRSVP").click(function(e){
e.preventDefault();
var nameArray = [];
//var uniqueCode = parseInt($(this).find('.theCheckbox').attr('id'));
//var response = ($(this).find('.theCheckbox').is(":checked")) ? '1' : '0';
//the parameters passed should be uniqueCode and response which both gave legit values
if($("#displayContacts").is(":visible")){
$.get("submitRSVP.php", {rs: '1', resp: '12345'})
.done(function(rtn){
console.log(rtn); //error is returned
})
}
});
Here is my php code:
<?php
require 'dbh.php';
$rsvp = $REQUEST["rs"];
$response = $REQUEST["resp"];
session_start();
if(session_start()) $invitationCode = $_SESSION['login_user'];
$hint = "here1";
try{
$updateQuery = "UPDATE `db686470460`.`GuestWithPlusOnes` SET `Confirmed`= '$response' WHERE `GuestWithPlusOnes`.`UniqueID`= '$rsvp'";
$updateStmt = $conn->prepare($updateQuery);
$updateStmt->execute();
if ($updateStmt->rowCount() > 0) {
$hint = 'success';
}else {
$hint = 'error';
}
$_SESSION['login_user'] = $rsvp;
$updateStmt = null;
}
catch(Exception $e){
$hint = $e;
}
echo $hint;
?>
I definitely have a record in my table with that uniqueId because when I change the query to:
$updateQuery = "UPDATE `db686470460`.`GuestWithPlusOnes` SET `Confirmed`= '1' WHERE `GuestWithPlusOnes`.`UniqueID`= '12345'";
that updates as normal. Is there something else I could be missing?
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);
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.
I have a jquery save script like :
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Your file is save as : '+ naam);
window.location.replace("index.php?id=latest");
}
else
{
alert('Not saved');
}
I save a div in save.php which creates an new id in the database
What I want to achive is were
window.location.replace("index.php?id=latest");
id=latest must become (id=id from last saved file).
I tried
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
window.location.replace("index.php?id="+MBId);
and
var MBID =
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo $MBId ?>
window.location.replace("index.php?id="+MBId);
They both failed.
How can I run the query in the if(naam !=null) statement?
At first place you must fix your jQuery POST... You don't use POST respond which is wrong.. You should wait for it and then continue with other actions
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam }, function(responde){
if(responde.id)
window.location.replace("http://yoururl.com/index.php?id="+responde.id);
else
alert("No responde...");
}, "json");
}
else
{
alert('Not saved');
}
For better results I suggest you to use JSON data in that post/respond..
At your PHP code you have to set:
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo json_encode(array('id'=>$MBId));
exit();
?>
P.S. For window.location.replace please set your FULL url: "http://localhost/index.php?id=" OR atleast put slash at start of it "/index.php?id="
Solution
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Uw moodboard is opgeslagen als '+ naam);
window.location.replace("index.php?id=<?php $q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = ($data[0] + 1); echo "$MBId";?>");
}
This Works for me , i didnt need to make a jquery var i could echo the variable in php.
And i had to add 1 cause the sql query is loaded when the page is loaded.
So the file isn't saved yet when i get the highest id.
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.