My app makes a call from Flash to get back list of countries but in my PHP the result is returning empty, i have created the table using phpMyAdmin and i have two rows in there.
Here is the code Action script 3:
package {
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.events.EventDispatcher;
public class SQL extends EventDispatcher{
var url:String = "";
var urlRequest:URLRequest;
public function SQL() {
// constructor code
}
public function Post(url:String, urlVaribles:URLVariables = null):void{
this.url = url;
this.urlRequest = this.urlRequestObj();
var loader:URLLoader = new URLLoader();
if(urlVaribles){
this.urlRequest.data = urlVaribles;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
}
loader.addEventListener(Event.COMPLETE, dataPostOnLoad);
loader.load(this.urlRequest);
}
public function Get(url:String, urlVaribles:URLVariables = null):void{
this.url = url;
this.urlRequest = this.urlRequestObj();
var loader:URLLoader = new URLLoader();
if(urlVaribles){
this.urlRequest.data = urlVaribles;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
}
loader.addEventListener(Event.COMPLETE, dataGetOnLoad);
loader.load(this.urlRequest);
}
private function urlRequestObj():URLRequest{
return new URLRequest(this.url);
}
private function dataPostOnLoad(evt:Event):void{
var evt2:SQLEvent=new SQLEvent(SQLEvent.POST_COMPLETE, evt.target.data);
dispatchEvent(evt2);
}
private function dataGetOnLoad(evt:Event):void{
trace("IN GET " + evt.target.data);
var evt2:SQLEvent=new SQLEvent(SQLEvent.GET_COMPLETE, evt.target.data);
dispatchEvent(evt2);
}
}
}
Code for the call from Flash:
import fl.motion.MotionEvent;
var sql:SQL = new SQL();
sql.addEventListener(SQLEvent.GET_COMPLETE, dataGetResponse);
sql.Get("http://localhost:8888/MAMP/HUGT/getCountriesDP.php");
mc_ddScroll.visible = false;
mc_ddScrollButton.addEventListener(MouseEvent.CLICK, clickScrollButton);
function dataGetResponse(e:SQLEvent):void {
trace("Countries " + e.params);
}
function clickScrollButton(e:MouseEvent):void{
if(mc_ddScroll.visible){
mc_ddScroll.visible = false;
}
else{
mc_ddScroll.visible = true;
}
}
And finally the PHP script:
getCountriesDP.php
<?php
include "connect.php";
$result = mysql_query($conn,"SELECT * FROM C_Countries");
if(mysql_num_rows($result)){
echo '{"countries":[';
$first = true;
$row=mysql_fetch_assoc($result);
while($row=mysql_fetch_row($result)){
// cast results to specific data types
if($first) {
$first = false;
} else {
echo ',';
}
echo json_encode($row);
}
echo ']}';
} else {
echo "[]";
}
mysqli_close($conn);
?>
Connect.php
<?php
$conn = mysql_connect("localhost","root","root");
mysql_select_db("HUGT", $conn);
// disable reporting errors for security reason
error_reporting(0);
// Error checking
if(!$conn) {
die('Could not connect ' . mysql_error());
}
?>
I just changed my php script to this:
<?php
$conn = mysqli_connect("localhost","root","root", "HUGT");
//mysql_select_db("HUGT", $conn);
// disable reporting errors for security reason
error_reporting(0);
// Error checking
if(mysqli_connect_errno()) {
die('Could not connect ' . mysqli_connect_error());
}
?>
and:
<?php
include "connect.php";
$result = mysqli_query($conn,"SELECT * FROM C_Countries");
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($conn);
?>
Related
So I have a live chat, and when the user clicks the button, this function should kick into action and insert it into the database and into the HTML conversation section.
The first problem is that if i use dataType: "json" , then it enters the AJAX error case instead of success. But if I pull it out, like below, it enters the success case. But here comes the second problem: only the first alert is displayed, and if I try to alert the response, it doesn't show anything (+neither the alert('yes') is displayed).
function sendMessage(to_user_id) {
message = $(".message-input input").val();
$('.message-input input').val('');
if($.trim(message) == '') {
return false;
}
$.ajax({
url:"chat_action.php",
method:"POST",
data:{to_user_id:to_user_id, chat_message:message, action:'insert_chat'},
success:function(response) {
alert('no');
var resp = JSON.parse(response);
$('#conversation').html(resp.conversation);
$(".messages").animate({ scrollTop: $('.messages').height() }, "fast");
alert('yes');
},
});
}
EDIT1:
It might be useful to understand my files:
I have index.php which contains the actual chat. When the send button is clicked, it accesses the chat.js file that contains the script above. Then, this is the part of chat_action.php that deals with it and passes it further to Chat.php.
chat_action.php
session_start();
include ('Chat.php');
$chat = new Chat();
if($_POST['action'] == 'insert_chat') {
$chat->insertChat($_POST['to_user_id'], $_SESSION['userid'], $_POST['chat_message']);
}
Chat.php
<?php
class Chat{
private $host = 'localhost';
private $user = 'root';
private $password = "";
private $database = "chat_demo";
private $chatTable = 'chat';
private $chatUsersTable = 'chat_users';
private $chatLoginDetailsTable = 'chat_login_details';
private $dbConnect = false;
public function __construct(){
if(!$this->dbConnect){
$conn = new mysqli($this->host, $this->user, $this->password, $this->database);
if($conn->connect_error){
die("Error failed to connect to MySQL: " . $conn->connect_error);
}else{
$this->dbConnect = $conn;
}
}
}
public function insertChat($reciever_userid, $user_id, $chat_message) {
$sqlInsert = "
INSERT INTO ".$this->chatTable."
(reciever_userid, sender_userid, message, status)
VALUES ('".$reciever_userid."', '".$user_id."', '".$chat_message."', '1')";
$result = mysqli_query($this->dbConnect, $sqlInsert);
if(!$result){
return ('Error in query: '. mysqli_error($this->dbConnect));
} else {
$conversation = $this->getUserChat($user_id, $reciever_userid);
$data = array(
"conversation" => $conversation
);
echo json_encode($data);
}
}
public function getUserChat($from_user_id, $to_user_id) {
$fromUserAvatar = $this->getUserAvatar($from_user_id);
$toUserAvatar = $this->getUserAvatar($to_user_id);
$sqlQuery = "
SELECT * FROM ".$this->chatTable."
WHERE (sender_userid = '".$from_user_id."'
AND reciever_userid = '".$to_user_id."')
OR (sender_userid = '".$to_user_id."'
AND reciever_userid = '".$from_user_id."')
ORDER BY timestamp ASC";
$userChat = $this->getData($sqlQuery);
$conversation = '<ul>';
foreach($userChat as $chat){
$user_name = '';
if($chat["sender_userid"] == $from_user_id) {
$conversation .= '<li class="replies">';
$conversation .= '<img width="22px" height="22px" src="userpics/'.$fromUserAvatar.'" alt="" />';
} else {
$conversation .= '<li class="sent">';
$conversation .= '<img width="22px" height="22px" src="userpics/'.$toUserAvatar.'" alt="" />';
}
$conversation .= '<p>'.$chat["message"].'</p>';
$conversation .= '</li>';
}
$conversation .= '</ul>';
return $conversation;
}
private function getData($sqlQuery) {
$result = mysqli_query($this->dbConnect, $sqlQuery);
if(!$result){
die('Error in query: '. mysqli_error($this->dbConnect));
}
$data= array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[]=$row;
}
return $data;
}
public function getUserAvatar($userid){
$sqlQuery = "
SELECT avatar
FROM ".$this->chatUsersTable."
WHERE userid = '$userid'";
$userResult = $this->getData($sqlQuery);
$userAvatar = '';
foreach ($userResult as $user) {
$userAvatar = $user['avatar'];
}
return $userAvatar;
}
}
EDIT2:
From the console:
chat.js:106
index.php:1 Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.success (chat.js:107)
at j (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at x (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
you try to parsing not valid json, in your js maybe try this:
function sendMessage(to_user_id) {
message = $(".message-input input").val();
$('.message-input input').val('');
if($.trim(message) == '') {
return false;
}
$.ajax({
url:"chat_action.php",
method:"POST",
data:{to_user_id:to_user_id, chat_message:message, action:'insert_chat'},
success:function(response) {
alert('no');
try {
var resp = JSON.parse(response);
$('#conversation').html(resp.conversation);
} catch(e) { alert(e) }
$(".messages").animate({ scrollTop: $('.messages').height() }, "fast");
alert('yes');
},
});
}
I am new to Angular2. I have one PHP file and would like to fetch content from PHP file in Angular component. Following is my code I have written by taking references. I am not able to figure out what is the issue as I am not getting any error in console nor desired output.
PHP code - 'getArea.php'
<?php
$link = mysql_connect('localhost', 'root', '');
mysql_select_db("mydb", $link);
$data=array();
$result = mysql_query("SELECT * FROM dam_color", $link);
$num_rows = mysql_num_rows($result);
for ($i=0; $i<mysql_num_rows($result); $i++)
{
$row = mysql_fetch_assoc($result);
$data['success'] = true;
$data['areaname'] = $row['area_name'];
}
echo json_encode($data);
?>
Angular Component - php-form.component.ts content
export class PhpFormComponent {
msg = "Welcome";
public data;
constructor(private http:Http){ }
ngOnInit(){
this.getData();
}
getData(){
this.http.get('http://localhost/myapi/getArea.php')
.map(res => res.json())
.map(res => {
if(res.success)
{
this.msg="Fetched data";
}
else
{
this.msg="Error in fetching data";
}
})
.subscribe(
data =>this.getdata = JSON.stringify(data),
err => console.error(err),
() => console.log('done')
);
}
}
I tried to link my actionscript3 application to the database ... Here are my codes.
MY AS3 CODE:
import flash.events.*;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLRequestMethod;
const SENT_SUCCESS:String = "Successful";
const SENT_FAILED:String = "Unsuccessful";
var tmr:Timer;
function resetTextFields():void {
username.text = String("username");
password.text = String("password");
}
function afterTmrWait(evt:TimerEvent):void {
tmr.stop();
tmr.removeEventListener(TimerEvent.TIMER, afterTmrWait);
}
function submitForm(evt:MouseEvent):void {
var passChecks:Boolean = true;
if(username.text == String("")) {
passChecks = false;<br>
}
if(password.text == String("")) <br>{<br>
passChecks = false;
}
if(passChecks) {
var urlVars:URLVariables = new URLVariables();
var urlReq:URLRequest = new URLRequest("php/login.php");
var ldr:URLLoader = new URLLoader();
urlVars.username = username.text;
urlVars.password = password.text;
urlReq.data = urlVars;
urlReq.method = URLRequestMethod.POST;
ldr.addEventListener(Event.COMPLETE, serverFeedback);
ldr.load(urlReq);
ldr.dataFormat = URLLoaderDataFormat.VARIABLES;
}
}
function serverFeedback(evt:Event):void {
var ldr:URLLoader = evt.target as URLLoader;
var urlVars:URLVariables = new URLVariables(ldr.data);
if(urlVars.result == SENT_SUCCESS) {
login_result.gotoAndStop(2);
resetTextFields();
} else if(urlVars.result == SENT_FAILED) {
login_result.gotoAndStop(3);
}
tmr = new Timer(3000, 1);
tmr.addEventListener(TimerEvent.TIMER, afterTmrWait);
tmr.start();
}
login_btn.addEventListener(MouseEvent.CLICK, submitForm);
resetTextFields();
MY PHP CODE:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if(exist($_POST['username']) && exist($_POST['password'])) {
$mysql = mysql_connect("host", "username", "password", "database");
$password = md5(stripslashes($mysql->real_escape_string($password)));
$outcome = $mysql->query("SELECT * FROM user WHERE username='{$username}' AND password='{$password}' LIMIT 1");
if(!$outcome->null_rows) {
echo( "result=Unsuccessful" );
} else {
echo( "result=Successful" );
}
}
?>
AND I GET THIS ERROR IN FLASH:
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
at Error$/throwError()
at flash.net::URLVariables/decode()
at flash.net::URLVariables()
at flash.net::URLLoader/onComplete()
PLEASE HELP ME, WHAT I DO WRONG?
The URLLoader dataFormat by default is text. You need to add
ldr.dataFormat=URLLoaderDataFormat.VARIABLES;
so it does throw an error when you try
var urlVars:URLVariables = new URLVariables(ldr.data);
set dataFormat before load request..
your code
ldr.load(urlReq);
ldr.dataFormat = URLLoaderDataFormat.VARIABLES;
try this....
ldr.dataFormat = URLLoaderDataFormat.VARIABLES;
ldr.load(urlReq);
I have a MySQL database and I access it through PHP script. The issue I have is that the variables returned from PHP are always the same.
First time I run the code (add/remove records in the database) every thing is correct, but if I'm running it again (add/remove) PHP reports back to AS3 the same records as before. running the php directly in the browser returns are correct.
hope someone can help me... I'm getting crazy!
here are my codes:
AS3
function sendSqlData(event:Event):void
{
playlistDateString = "&playlistDateString="+playlistDate.getFullYear().toString()+monthDigit+playlistDate.getMonth().toString()+dayDigit+playlistDate.getDate().toString();
playlistSongNr = "&playlistSongNr="+ song;
songTime ="&songTime="+ Math.floor(channel.position);
var phpUrl:String = "send_data.php";
var phpUrlRequest:URLRequest = new URLRequest(phpUrl+parseMe+playlistDateString+playlistSongNr+songTime);
scriptLoader = new URLLoader();
scriptLoader.addEventListener(Event.COMPLETE, sendSqlDataComplete);
scriptLoader.load(phpUrlRequest);
}
function getSqlData(event:Event):void
{
var phpUrl:String = "get_data.php";
var phpUrlRequest:URLRequest = new URLRequest(phpUrl+parseMe);
// phpUrlRequest.method = URLRequestMethod.POST;
scriptLoader = new URLLoader();
// scriptLoader.dataFormat = URLLoaderDataFormat.TEXT;
scriptLoader.addEventListener(Event.COMPLETE, getSqlDataComplete);
scriptLoader.load(phpUrlRequest);
}
function sendSqlDataComplete(event:Event):void
{
scriptLoader.removeEventListener(Event.COMPLETE, sendSqlDataComplete);
var phpVars:URLVariables = new URLVariables();
phpVars.decode(event.target.data);
getSqlData(event);
}
function getSqlDataComplete(event:Event):void
{
scriptLoader.removeEventListener(Event.COMPLETE, getSqlDataComplete);
var phpVars:URLVariables = new URLVariables();
phpVars.decode(event.target.data);
var phpString = event.target.data.toString();
var patterns:Array = ["id\\d{0,5}=\\d{0,5}", "playlistDate\\d{0,5}=\\d{0,8}", "playlistSongNr\\d{0,5}=\\d", "songTime\\d{0,5}=\\d{0,7}"];
for (var j:int = 0; j < 4; j++)
{
var pattern:RegExp = new RegExp(patterns[j],"g");
var tempStrings:Array = phpString.match(pattern);
for (i = 0; i < Number(phpVars.records); i++)
{
switch (j)
{
case 0:
ids[i] = Number(tempStrings[i].substring( tempStrings[i].indexOf("=")+1 ));
break;
case 1:
playlistDates[i] = Number(tempStrings[i].substring( tempStrings[i].indexOf("=")+1 ));
break;
case 2:
playlistSongNrs[i] = Number(tempStrings[i].substring( tempStrings[i].indexOf("=")+1 ));
break;
case 3:
songTimes[i] = Number(tempStrings[i].substring( tempStrings[i].indexOf("=")+1 ));
break;
}
}
tempStrings = null;
}
fillDataGrid(Number(phpVars.records));
}
PHP: send_data.php
<?php
include_once ('connect.php');
$playlistDateString = trim($_GET['playlistDateString']);
$playlistSongNr = trim($_GET['playlistSongNr']);
$songTime = trim($_GET['songTime']);
if($connection)
{
$status .= ("connect=ok&");
//Select database
mysql_select_db($dbname, $connection);
$sql="INSERT INTO $tablename1 (ID, playlistDate, playlistSongNr, songTime, comment) VALUES ('', '$playlistDateString', '$playlistSongNr', '$songTime', 'comment');";
$status .= ("sql=".$sql."&");
// Execute query
if (mysql_query($sql,$connection) )
{
$status .= ("query=ok");
}
else
{
$status .= ("query=error:".mysql_error());
}
}
else
{
$status = ("connect=error: ".mysql_error());
}
echo $status;
mysql_close($connection);
?>
PHP get_data.php
<?php
include_once ('connect.php');
if($connection)
{
$status .= ("connect=ok");
//Select database
mysql_select_db($dbname, $connection);
//Execute query
$query = mysql_query("SELECT * FROM $tablename1");
if ($query)
{
$result = "records=".(mysql_num_rows($query));
$i = 0;
while ($row = mysql_fetch_array($query))
{
$result .= "&id".$i."=".($row["ID"]);
$result .= "&playlistDate".$i."=".($row["playlistDate"]);
$result .= "&playlistSongNr".$i."=".($row["playlistSongNr"]);
$result .= "&songTime".$i."=".($row["songTime"]);
$result .= "&comment".$i."='".($row["comment"])."'";
$i++;
}
$status .= ("&receive=ok");
echo $result."&";
}
else
{
$status .= ("&receive=error");
}
}
else
{
$status .= ("connect=error:".mysql_error());
}
echo $status;
mysql_close($connection);
?>
It seems that your response is being cached when you call it from ActionScript. You can add a microtime value to the end of the URL (which will prevent caching).
var phpUrl:String = "get_data.php?" + new Date().getTime();
I am trying to create a user log-in system in Flash but I need to communicate to MySQL through PHP in order to do so. I looked around at a few tutorials, but I have been getting errors.
Here is the interface I have made in flash, which I am trying to communicate with controlpanel.php
http://i.imgur.com/JrTWm.png?1
Here is the code
AS file
package actions
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLLoader;
import flash.events.Event;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequestMethod;
import flash.text.TextFieldAutoSize;
public class main extends MovieClip
{
public function main():void
{
submit_button.buttonMode = true;
submit_button.addEventListener(MouseEvent.MOUSE_DOWN, checkLogin)
username.text = "";
password.text = "";
}
public function checkLogin(e:MouseEvent):void
{
if(username.text==""||password.text=="")
{
if (username.text == "")
{
username.text = "Enter your username";
}
if (password.text == "")
{
password.text="Enter your password";
}
}
else
{
processLogin();
}
}
public function processLogin():void
{
var phpVars:URLVariables = new URLVariables();
var phpFileRequest:URLRequest = new URLRequest("http://mathlympics.cu.cc/php/controlpanel.php");
phpFileRequest.method = URLRequestMethod.POST;
phpFileRequest.data = phpVars;
var phpLoader:URLLoader=new URLLoader();
phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
phpVars.systemCall = "checkLogin";
phpVars.username = username.text;
phpVars.password = password.text;
phpLoader.load(phpFileRequest);
phpLoader.addEventListener(Event.COMPLETE, showResult);
}
public function showResult(event:Event):void
{
result_text.autoSize = TextFieldAutoSize.LEFT;
result_text.text = ""+ event.target.data.systemResult;
}
}
}
PHP file - connect.php
<?php
$db_username = "censored";
$db_name = "censored";
$db_password = "censored";
$db_host = "mysql2.000webhost.com";
mysql_connect($db_host,$db_username, $db_password, $db_name);
mysql_select_db($db_name) or die (mysql_error());
?>
PHP file - controlpanel.php
<?php
error_reporting(E_ALL);
include_once("connect.php");
$username = "admin";
$password = "password";
$sql = "SELECT * FROM user WHERE username='$username' AND password='$password'";
$query = mysql_query($sql);
$login_counter = mysql_num_rows($query);
if ($login_counter > 0)
{
$data = mysql_fetch_array($query);
$userbio = $data["user_bio"];
echo "systemResult=" . $userbio;
}
else
{
echo "systemResult=Invalid";
}
?>
I do not get any error but when I press the submit button, is says undefined in the result text box, even when I type the right username and password.
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
To those of you interested: Here is my website enter link description here
So the problem ended up being you had SELECT * FROM user... when it should have been SELECT * FROM users... =)