Sending POST data from actionscript 3.0 to PHP - php

I have a actionscript game that send data to a php with POST.
But I don't know how to make it working, first to get the data in php then to insert in database.
Here is the ActionScript, a part from game that send the post to php.
public function post()
{
var _loc_1:* = new ByteArray();
_loc_1.writeUnsignedInt(1);
_loc_1.writeUnsignedInt(this.Args.u);
_loc_1.writeUnsignedInt(this.Args.r);
_loc_1.writeUnsignedInt(this.Args.t);
_loc_1.writeUnsignedInt(this.Args.p);
_loc_1.writeUnsignedInt(this.apples);
_loc_1.writeUnsignedInt(this.calories);
_loc_1.writeUnsignedInt(this.StartTime);
var _loc_2:* = 0;
while (_loc_2 < this.moves.length)
{
_loc_1.writeShort(this.moves[_loc_2]);
_loc_2 = _loc_2 + 1;
}
var _loc_3:* = new URLRequestHeader("Content-type", "application/octet-stream");
var _loc_4:* = new URLRequest("http://mywebsite.com/Game.php");
_loc_4.requestHeaders.push(_loc_3);
_loc_4.method = URLRequestMethod.POST;
_loc_4.data = _loc_1;
var _loc_5:* = new URLLoader();
_loc_5.load(_loc_4);
_loc_5.addEventListener(Event.COMPLETE, this.PostCallback);
return;
}// end function
public function PostCallback(param1)
{
this.tf.text = "PHP:" + param1.currentTarget.data;
return;
}// end function
Somewhere is the this.post();(is used when game is finished and win)
This is the data what i want to get in php, is like a scores:
var _loc_1:* = new ByteArray();
_loc_1.writeUnsignedInt(1);
_loc_1.writeUnsignedInt(this.Args.u);
_loc_1.writeUnsignedInt(this.Args.r);
_loc_1.writeUnsignedInt(this.Args.t);
_loc_1.writeUnsignedInt(this.Args.p);
_loc_1.writeUnsignedInt(this.apples);
_loc_1.writeUnsignedInt(this.calories);
_loc_1.writeUnsignedInt(this.StartTime);
Page Game.php
<?php
$dbhost = 'localhost';
$dbname = 'dbname';
$dbuser = 'root';
$dbbg = 'pass';
mysql_connect($dbhost, $dbuser, $dbbg)or error("Could not connect: ".mysql_error());
mysql_select_db($dbname) or error(mysql_error());
if(isset($HTTP_RAW_POST_DATA))
{
mysql_query("INSERT INTO game (gameinfo) VALUES ('".$HTTP_RAW_POST_DATA."');");
}
?>
It insert me in database a text like with nonsense characters.. 'YPDèU"ˆ†U"~µIk€†œ«¹ãV„–' I am appreciate any hand of help.

Related

Json/ajax post with numerals works, returns empty if using non-numeric values. What's the proper method for this?

I'm using URL hashes to request data from my database, such as "url.com/content/book.html#132" in this format:
$(document).ready(function(){
var number = window.location.hash.substr(1);
$.ajax({
type:'POST',
url:'./db/db.php',
dataType: "json",
data:{number:number},
success:function(data){
if(data.status == 'ok'){
$('#title').text(data.result.title);
$('#author').text(data.result.author);
$('#genre').text(data.result.genre);
etc...
}
}
});
});
and in PHP:
<?php
if(!empty($_POST['number'])){
$data = array();
//database details
$dbHost = '******';
$dbUsername = '******';
$dbPassword = '******';
$dbName = '******';
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($db->connect_error){
die("Unable to connect database: " . $db->connect_error);
}
$query = $db->query("SELECT * FROM db WHERE id = {$_POST['number']}");
if($query->num_rows > 0){
$userData = $query->fetch_assoc();
$data['status'] = 'ok';
$data['result'] = $userData;
}else{
$data['status'] = 'err';
$data['result'] = '';
}
echo json_encode($data);
}
?>
This works perfectly. However, I'd also like to pull up data on another page based on genre, which I would also like to set with the URL, as in
"url.com/content/genre.html#history"
In my ajax, I simply changed the variable to 'genre' and data:{genre:genre}. In my PHP I'm selecting like this:
$query = $db->query("SELECT * FROM db WHERE genre = {$_POST['genre']}");
but it doesn't work and I even get a blank when testing with print_r ($_POST['genre']); and a console.log(gengre); shows the hash is being read correctly. What am I missing?
For those interested, I found the answer, and of course it was much simpler than I was expecting. JSON.stringify()
So:
var hash = window.location.hash.substr(1);
var genre = JSON.stringify(hash);
This turns the value into a json object.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

As3 + PHP error

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

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.

passing data from javascript to php using Jquery

Maybe this question has been asked before but I am struggling in doing this. I have got a php file which does not include any piece of php code (might be in the future),it includes just javascript and some html. What I want to do is clicking a button in this php file to send some amount of data to another php file.
put it this way..
1-I have got a saveProfile function in a.php and a button is calling this function
function saveProfile (){
var variableD = 'sample data';
$.post("dbConn.php", { js: variableD});
}
2-I have got another php which is called dbConn.php that receives data and stores in a database table.
I have found so many examples. I have applied them but it still does not work and is driving me nuts. I am a java programmer but new in php.
Any help is appreciated.give me some clean sample code or if you see any mistake please kindly warn me. Thanks to all in advance...
Regards.
Ozlem.
Take a look at the accepted answer to "Javascript Post Request like a Form Submit".
It provides javascript for for:
function post_to_url(path, params, method) {
...
}
I think this will do what you want.
Thanks for all the answers. I have solved the problem. The data had being passes but I was not able to handle it properly. I just add a dummy code to test it.It worked. I will upload the code after I have finished.Thanks to all.
This function is in a PHP file, but is full of JS code. The last line passes the data to another PHP file which saves the data into a database.
function saveProfile (){
var _profileId = 0;
var _profileName = document.getElementById('nameProfile').value;
var queryArr=[];
$(markersArray).each(function (index){
//alert(markersArray[index].name);
var _locationId = index;
var _locName = markersArray[index].name;
var _markerLat = markersArray[index].marker.getLatLng().lat();
var _markerLng = markersArray[index].marker.getLatLng().lng();
var locations = {
profileName: _profileName,
locationId:_locationId,
locationName:_locName,
lat:_markerLat,
lng:_markerLng }
queryStr = { "locations": locations}
queryArr.push(queryStr);
});
/*for ( var i=0; i<markersArray.length; i++){
alert(queryArr[i].locations.locationId+"--"+queryArr[i].locations.locationName +"--"+queryArr[i].locations.lat);
}*/
$.post('dbConn.php', { opType:"saveAsProfile" , data: queryArr}, showResult, "text");
}
This is dbConn.php, which is called by the saveProfile method. The data is handled as follows:
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'google_map_db';
$opType = $_POST['opType'];
//SAVE PROFILES WITH A PROFILE NAME
if(!strcmp($opType, "saveAsProfile") ){
$res = $_POST['data'];
$connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error() );
mysql_select_db( $db_name ) or die( mysql_error() );
$queryString = "";
for($i = 0; $i < sizeof($res); $i++){
$profileName = $res[$i]['locations']['profileName'];
$locationId = $res[$i]['locations']['locationId'];
$locationName = $res[$i]['locations']['locationName'];
$lat = $res[$i]['locations']['lat'];
$lng = $res[$i]['locations']['lng'];
$sp = " ";
$queryString = $queryString . "(0 ".",'".$profileName."',".$locationId.",'".$locationName."',".$lat.",".$lng.") ";
if($i<sizeof($res)-1)
$queryString = $queryString . ", ";
}
$qInsertUser = mysql_query(" INSERT INTO `map_locations` (`profileId`, `profileName`, `locationId`, `locationName`, `lat`, `lng`)
VALUES ".$queryString." ");
if ($qInsertUser){
echo "successfully added!!!";
} else {
echo "Error";
}
}

Categories