How to interact with PHP via getURL in actionscript? - php

getURL('http://www.google.com',_blank);
The above can open google.com,but how to fetch data from server side(PHP) on localhost?

I found this tutorial
<?
$first="this";
$second = "that";
echo "myfirst=$first&mysecond=$second";
exit;
?>
Flash Actionscript:
var lvSend = new LoadVars();
var lvReceive = new LoadVars();
lvSend.SendAndLoad("www.domain.com/script.php",lvReceive,"POST");
lvReceive.onLoad = function(bSuccess) {
if(bSuccess == true) {
trace(this.myfirst);
trace(this.mysecond);
}
}

Related

AngularJS $http.get() not working

I am using ZF2 and AngularJS to create a Quiz Application. When I am running the code, No error occurs, and no result.
(function(angular) {
function MainController($scope,$http) {
$scope.question = function(id)
{
var site = "http://localhost/zf/public/interviewer";
var page = "/jsonquestion/"+id;
alert(site + page);
var reqQuestion = $http.get(site + page);
reqQuestion.success(function(data, status, headers, config) {$scope.question.questions = data;});
reqQuestion.error(function(data, status, headers, config){alert("AJAX failed!");});
alert(data);
}
};
angular.module("app", []).controller("MainController", ["$scope", MainController]);
})(angular);
My zend part is
public function jsonquestionAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
$questions = $this->getQuestionsTable()->getQuestions($id);
$result = json_encode($questions);
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($myfile, $result);
fclose($myfile);
echo $result;
return $result;
}
When I m calling http://localhost/zf/public/interviewer/jsonquestion/1 from browser its working and returning Json
You aren't injecting $http to your controller
Try changing to this.
angular.module("app", []).controller("MainController", ["$scope", "$http", MainController]);
Shot in the dark. Your zend function is called jsonquestionAction, but your page call is made to jsonquestion.
Maybe changing this:
var page = "/jsonquestion/"+id;
To this:
var page = "/jsonquestionAction/"+id;
Will help.

Upload file from flash to server PHP

I'm going to upload files from flash to server. When user begin, input his username, then I send it to php, this way:
var myusername:String = username.text;
username.restrict = "A-Za-z0-9";
login_btn.addEventListener(MouseEvent.CLICK,login);
function login (evt:MouseEvent):void{
var loader : URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("http://domain/uploads/upload.php");
request.method = URLRequestMethod.POST;
var variables:URLVariables = new URLVariables();
var userid:String = myusername;
variables.ID = userid;
request.data = variables;
loader.load(request);
}
upload.php :
<?php
$myuser = $_POST['ID'];
$uploads_dir = './uploads/'.$myuser;
if( $_FILES['Filedata']['error'] == 0 ){
if( move_uploaded_file( $_FILES['Filedata']['tmp_name'],
$uploads_dir.$_FILES['Filedata']['name'] ) ){
exit();
}
}
echo 'error';
exit();
?>
The problem is that files upload to uploads folder not in user folder. Anyone could help me please?
What is the value of $_POST['ID']?
I don't see you setting that anywhere in the request. There's this:
variables.UID = userid;
But wouldn't that be $_POST['UID'] and not $_POST['ID']?

Capture form response in Javascript?

Let say I submit data to a form with the following code
var xhr = new XMLHttpRequest(), formData = new FormData();
formData.append("img", img);
formData.append("user", localStorage["username"]);
formData.append("pass", localStorage["password"]);
xhr.onreadystatechange = function (event) {
if (xhr.readyState === 4 && xhr.status === 200) {
var value = xhr.responseText; // value should equal "1234"
alert( "value = " + value );
}else{
alert("none");
}
};
xhr.open("POST", "http://joubin.me/uploads3/upload_file.php", true);
xhr.send(formData);
After upload.php is done, it redirects to another page called giveid.php and the only thing it displays is a text string with an id
say 1234
How can I with javascript capture this exact id.
Keep in mind, a different upload.php redirect will have a different id number on giveid.php?
I looked into the xmlhtml responses and could not figure it out.
Here is what form goes
$password = $_REQUEST['pass'];
$username = $_REQUEST['user'];
$image = $_REQUEST['img'];
echo $password;
echo "<br/>";
echo $username;
echo "<br/>";
echo $image;
$con = mysql_connect("localhost","ya","right");
if (!$con)
{
die('Could not connect: ' . mysql_error());
echo "could not connect";
}
$asql = "SELECT * FROM `ashkan`.`users` where user='$username' and pass='$password';";
$result = mysql_query($asql);
echo $result;
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
echo $count;
echo 11;
if($count == 1){
$sql = "INSERT INTO `ashkan`.`goog` (`user`, `pass`, `img`) VALUES ('$username', '$passwo$
}
mysql_query($sql);
mysql_close($con);
header( 'Location: giveid.php' ) ;
and here is the content of giveid.php
1234
Any help would be great.
Thanks
You need to use xhr.onreadystatechange to retrieve the response from the server.
Something like this might work.
var value;
var formData = new FormData();
formData.append("img", img);
formData.append("user", localStorage.username);
formData.append("pass", localStorage.password);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (event) {
if (xhr.readyState === 4 && xhr.status === 200) {
value = xhr.responseText; // value should equal "1234"
alert( "value = " + value );
}
};
xhr.open("POST", "upload.php", true);
xhr.send(formData);
Info Here: http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php
Remember that header() must be called before any actual output is sent. So get rid of all the echos you have in the php file. Once you echo then that starts the output buffer for the response to the client.
Info Here: http://php.net/manual/pt_BR/function.header.php
I think this should be your only echo on the php page.
echo include( 'giveid.php');
Try using Google Chrome Dev Tool Network tab to view the response from your php webpage.
Launch Google Chrome,
Hit f12,
Click the network tab,
reload your page,
click on the ajax response page,
click preview to view the response.
Info Here: https://developers.google.com/chrome-developer-tools/docs/network
xhr documentation
Get xhr.response then parse it.
We usually return a json string so js can parse it easily.
googled xhr example
something like this:
xhr.onreadystatechange=function()
{
if (xhr.readyState!=4 || xhr.status!=200)
return;
var resp = xhr.responseText;
var parsed = eval(resp);
}

PHP and AJAX image header not being read

I use the script below to create images on the fly, and display them via ajax and a div however the PHP image header is not being read and instead of an image been displayed I just get the image source code. Any ideas how force php to read the header as an image?
<?php
header('Content-Type: image/jpeg'); // JPG picture
$root = $_SERVER['DOCUMENT_ROOT'];
require("$root/include/mysqldb.php"); //mysql login details
require("$root/include/mysql_connect.php"); //mysql connect
if(!empty($small)) { $size = "50"; $folder = "thumnail_user_images"; } else { $size = "250"; $folder = "large_user_images"; }
$dice_image = $_GET["image"];
if (!file_exists("$root/$folder/$dice_image"))
{
require("$root/include/image_resizing_function.php"); //create image
$image = new SimpleImage();
$image->load("$root/raw_user_images/$dice_image");
$image->resizeToWidth($size);
$image->save("$root/$folder/$dice_image");
$image->output();
}
else {
readfile("$root/$folder/$dice_image");
}
And this is the Ajax a use to swap out the images:
<script type="text/javascript">
var bustcachevar=1
var loadedobjects=""
var rootdomain="https://"+window.location.hostname
var bustcacheparameter=""
function ajaxpage(url, containerid){
var page_request = false
if (window.XMLHttpRequest)
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
if (bustcachevar)
bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
}
function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}
function loadobjs(){
if (!document.getElementById)
return
for (i=0; i<arguments.length; i++){
var file=arguments[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){
if (file.indexOf(".js")!=-1){
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" "
}
}
}
</script>
Make sure there's no extra whitespace after the closing ?> in the php files referenced by require statements. I had that problem and was scratching my head for days before finding the answer.

How to GET variable as instance from PHP after POST by flash actionscript

Hi I'm working on actionscript, saving a raw image from camera then POST with save.php then
I want save.php echo back the variable which is a file name that have just generated by save.php to actionscript
see this line:
var urlParameter:String = "images/test_01.php?img=" + "myfileURL";
navigateToURL(new URLRequest(urlParameter), "_blank");
Thanks in advance
this is AS3 code
function onSaveJPG(e:Event):void{
var myEncoder:JPGEncoder = new JPGEncoder(100);
var byteArray:ByteArray = myEncoder.encode(bitmapData);
var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var saveJPG:URLRequest = new URLRequest("save.php");
saveJPG.requestHeaders.push(header);
saveJPG.method = URLRequestMethod.POST;
saveJPG.data = byteArray;
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, sendComplete);
urlLoader.load(saveJPG);
function sendComplete(event:Event):void{
warn.visible = true;
addChild(warn);
warn.addEventListener(MouseEvent.MOUSE_DOWN, warnDown);
warn.buttonMode = true;
}
function warnDown(e:MouseEvent):void{
var urlParameter:String = "images/test_01.php?img=" + "myfileURL";
navigateToURL(new URLRequest(urlParameter), "_blank");
// navigateToURL(new URLRequest("images/"), "_blank");
// +saveJPG:URLRequest
// navigateToURL(new URLRequest("images/test_01.php?img=+saveJPG:URLRequest"), "_blank");
warn.visible = false;
}
} // move onSave JPG
} close to here instead of after sendComplete
warn.visible = false;
this is save.php
<?php
if(isset($GLOBALS["HTTP_RAW_POST_DATA"])){
$jpg = $GLOBALS["HTTP_RAW_POST_DATA"];
$img = $GET["img"];
$filename = "images/poza". mktime(). ".jpg";
file_put_contents($filename, $jpg);
echo "thisPic=" . $filename;
// echo $filename;
} else{
echo "Encoded JPEG information not received.";
}
?>
In your case you are just using mktime() for the file name, and images/poza is hard coded. You can post the file name along the jpeg data from flash, and when onSaveJPG is called you simply display the file name to the user.
Below is example of how you can send file_name.
var JPGFileName = YOUR TIME FUNCTION
var saveJPG:URLRequest = new URLRequest("save.php?file_name=" + JPGFileName);
saveJPG.requestHeaders.push(header);
saveJPG.method = URLRequestMethod.POST; saveJPG.data = byteArray;

Categories