I have a flash player embedded on page page.php?user=john using swfobject. The player calls the xml file content.php to get the results. I'm trying to get the user name from the url id. and fetch results based on that. I can get the username on page.php by doing $_GET['user'], but how can i pass that to content.php. Having read allot of articles online, i did the following,
I'm embedding the flash on page.php using swfobject like this
<script type="text/javascript">
var flashvars = {user:"<?php $_GET[user] ?>"};
var so = new SWFObject("<?php echo $index->CFG['site']['url'];?>preview2.swf", "sotester", "1000", "400", "8", "#000000", flashvars);
so.addParam("allowFullScreen", "true");
so.addParam("scale", "noscale");
so.addParam("menu", "false");
so.write("flashcontent");
</script>
In my AS2 file end of the file looks like
var paramList:Object = this.root.loaderInfo.parameters;
trace(paramList["user"])
xmlData = new XML();
xmlData.ignoreWhite = true;
xmlData.onLoad = loadXML;
xmlData.load("contentp.php?user=" + user);
So basically, i'm trying to pass $_GET['user'] from page.php to my swf file which calls content.php. Then swf would pass that value to content.php. I believe i provided you with all the information needed. Any help would be appreciated.
PS: right now as i have it, looking at console, i see Request URL:http://www.domain.com/content.php?user=undefined. So it's coming as undefined.
Embed like so with SWFObject v2.2
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
function loaded( ){
var flashvars = { };
flashvars.user = "<?php $_GET[user] ?>";
var params = {};
params.menu = "false";
params.quality = "high";
params.bgcolor = "#869ca7";
params.allowFullScreen = "true";
params.scale = "noscale";
var attributes = {};
attributes.id = "myFlashObject";
attributes.name = "myFlashObject";
attributes.align = "middle";
attributes.allowFullScreen = "true";
attributes.scale = "noscale";
var tmp = "expressInstall.swf";
var version = "8.0.0";
var width = "1000";
var height = "400";
var container = "sotester"
// verify the URL is correct
var flashObj = "<?php echo $index->CFG['site']['url'];?>preview2.swf";
swfobject.embedSWF(flashObj, container, width, height, version, tmp, flashvars, params, attributes);
}
</script>
</head>
<body onLoad="loaded()">
<div id="sotester">Loading Content... put alt. content here</div>
</body>
</html>
// in actionscript 3
var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
var user: String = String( paramObj[user] );
trace( user );
[EDIT]
// in actionscript 2
// _level0 will have the global flashvar on it
// trace(user);
REFERENCE
There are a few ways to go about this. If you want to insert flashvars into an embedded swf, you can simply use the flashvar property on the object or embed tags:
<param name="flashvars" value="uId=<?= $_GET['user'] ?>" />
Another way to do this is to have Flash retrieve the userId itself. Because flash can call javascript, you can actually do the same thing like this:
if( ExternalInterface.available ) {
ExternalInterface.call( "function() { return window.location.href; }" );
}
This will actually return the full URL string to flash itself, wherein you can do all the substring operations you desire.
Related
Lets say I have a public html page on the internet with the following content:
<html>
<head>
<script>
var variableA = {
name: "A"
};
variableA.id = 1;
</script>
</head>
<body>
...
</body>
</html>
Is there a way to get the value of the variable variableA with php?
Something like this:
$html = file_get_contents($myUrl);
$variableA = magicMethodIamLookingFor("variableA");
print_r($variableA);
With this result:
Array(
"name" => "A",
"id" => 1
)
I could do it just with regex and json_decode (similar like How to get Javascript variable from an HTML page?) but the problem is, that its not just a single json, but there are also variable changes like variableA.id = 1;
Note: With plain PHP scripting, it is not possible to access JS vars.
Interesting requirement. Below goes a solution. Lets consider the case if the variable name is passed in the URL. Let the page name be 'index.php'. The browsing URL looks like this localhost/index.php?varName=variableA, where varName is the query param which takes variable name as value. We can pass comma separated values also by tweaking the code a bit. But that is not considered now.
Outlining the steps below
Get contents of url.php and place it in a hidden div of index.php
Beneath the captured content, call an Ajax function with var name & var value as param.
Inside the ajax page, save the name / value to some DB or file.
After the ajax call there is some more DOM where we will print the name / value & remove the record from DB or File after displaying the same.
NB: The main code is in JS - See getVarWithValue(variable) function.
<html>
<body>
<?php
$varName = (isset($_GET['varName']) && trim($_GET['varName']) != "") ? $_GET['varName'] : 'variableA';
?>
<div style="display:none">
<?php
$html = file_get_contents('./url.php');
echo $html;
?>
<script>
//THIS IS THE CORE FUNCTION WHICH GETS THE VAR NAME & VALUE
function getVarWithValue(variable) {
var param = '';
for (var name in this) {
keyValue = [];
if (variable == name ) return param += name+'='+JSON.stringify(eval(name));
}
return false;
}
var http = new XMLHttpRequest();
http.open("POST", "setVariableValue.php", false); // 3rd argument makes sure that the call is NOT async.
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
document.getElementById("varValue").innerHTML = http.responseText.toString();
}
};
http.send(getVarWithValue( '<?php echo $varName ?>' ));
</script>
</div>
<?php
//$varValue = getValuefromDB(); Get the saved value from DB or file
echo "The variable value of $varName is: ".$varValue;
// Write code to remove the row from DB or file
?>
</body>
url.php (Page from which we need to capture the variable name & value)
<html>
<head>
<script>
var variableA = { name: "A" };
variableA.id = 1;
var variableB = ["Stack", "Overflow"]
</script>
</head>
<body>
Some Text
</body>
</html>
setVariableValue.php
<?php
/**
* Write code for saving var name & value to DB or file
*/
I am trying to use AngularJS to access a PHP variable. Here is my HTML and Angular code:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="mainCtrl">
Your Link: <div> <span ng-bind="fetchLink.link"></span></div>
</div>
<script>
angular.module('myApp', [])
.controller('mainCtrl', ['$http', function($http) {
var self = this;
self.link = "";
self.newTodo = {}; //Keys (as in key: value pairs) are automatically created when declared in form
var fetchLink = function() {
return $http.get('link.php').then(
function(response) {
self.link = response.data;
}, function(errResponse) {
console.error('Error while fetching notes');
});
};
}]);
</script>
</body>
</html>
And here is my PHP:
<?php
{ $link = 0x00;
"link":[{$link}];
$link= ($link + 1);
}
?>
I am trying to use the Angular code to access the 'link' variable that has to be updated each time it is accessed by any user (a hexidecimal value that is increased by 1). This is so that each user gets a unique link which they can access and share with their friends. When i preview the html page it just says your link: without any value next to it. I also thought about using a JSON object which I believe plays nicely with Angular, but I don't know if JSON objects can be updated with each use (because they are a client-side object, not server side).
<?php
$link = "http://example.com/".time();
echo json_encode(array("link"=>$link));
?>
Use time() and something else like rand() for create unique link and return link in json using json_encode() function.
I want to get value of $security_code which is in captchaCode.php file, in captcha.php file through javascript.I can not include this file in captcha.php file . Here is the code of Captcha_code.php and this code not comes inside any function of this file:
$captcha = new CaptchaCode();
$security_code = str_encrypt($captcha->generateCode(6));
And here is my javascript function, through this function i want to get the value of $security:
function refresh_captcha()
{
var img = document.getElementById('captcha_img');
img.src = '<?php echo "/captcha_images.php"?>';
jQuery("#captcha_img").attr("src",img.src);
jQuery("#security_code").val("<?php echo $security_code;?>");
}
Actually this code is for getting new encrypted value when captcha is refreshed without refreshing the page.
You have to change the image source assignment related code. No need to assign PHP tag. Just assign the PHP file name instead like this.
function refresh_captcha()
{
var img = document.getElementById('captcha_img');
img.src = '/captcha_images.php';
jQuery("#captcha_img").attr("src",img.src);
/*This line will not work without Ajax request*/
/*jQuery("#security_code").val("<?php echo $security_code;?>");*/
}
Send an ajax request to a page to output only the code like:
File: outputcode.php (demo only)
$captcha = new CaptchaCode();
$security_code = str_encrypt($captcha->generateCode(6));
echo $security_code;
exit;
Next, grab that value using AJAX, like for example in jQuery
$("#refresh_code").on('click', function() {
$.get("outputcode.php", function(data) {
//data will now hold the new code
});
});
Hope this gives you an idea.
If you cannot include the files, you need to use ajax request.
captcha.php
$captcha = new CaptchaCode();
$security_code = str_encrypt($captcha->generateCode(6));
echo json_encode($security_code);
in your js:
<img src="" id="captcha_img" onclick="refresh_captcha()"/>
<script>
function refresh_captcha()
{
$.ajax({
url : 'captcha.php',
type : 'POST',
dataType : 'json',
success : function (security_code) {
var source = security_code;
var img = document.getElementById('captcha_img');
img.src = source;
jQuery("#captcha_img").attr("src",img.src);
jQuery("#security_code").val(source);
}
});
}
</script>
The onclick event on the img could be totally wrong, but for the excercise purpose, I've put it there.
Depends on what $security_code is, you can for example, not use JSON.
In your php file captcha.php,
$captcha = new CaptchaCode();
$security_code = str_encrypt($captcha->generateCode(6));?>
<script>
var code = '<?= $security_code ?>';
</script><?php // rest of the php codes
In your js file
function refresh_captcha()
{
var img = document.getElementById('captcha_img');
img.src = code;
jQuery("#captcha_img").attr("src",img.src);
}
I have .js and .php files and html pages. I am including js files in html files and php files in js files.
I want to pass 'cat' value from js file to php file using address bar when I go to this page;
/demo/convert.html?cat=volume
But I have no idea how to do this.
By the way, this is a blacberry project and I am not sure if I can use address bar to pass value. Any idea is welcome.
Test this sample code with an URL like :
http://sputnick-area.net/test/index.php?foobar=works_as_a_charm
<?php
$var = $_GET['foobar'];
echo <<<EOF
<html>
<head>
<title></title>
</head>
<body>
demo of using PHP GET variable in Javascript :
<script type="text/javascript">
alert("$var");
</script>
</body>
</html>
EOF
?>
Edit :
if you'd like to handle GET variables from within JavaScript, consider the following HTML + JavaScript sample : http://sputnick-area.net/test/index.html?foobar=works_as_a_charm
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var vars = [], hash;
var hashes = window.location.href.slice(
window.location.href.indexOf('?') + 1
).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
alert(vars['foobar']);
</script>
</body>
</html>
Sure you can. When your JS function is called, you would have to do something like this:
function someFunction(someParameters) {
//Do whatever you need to do
window.location = "/demo/convert.html?variableName=" + variable;
}
This will cause a page reload with the new variable accessible through PHP in the $_GET array. For example:
<?php
$name = $_GET['variableName'];
if(length($name) < 3) {
echo "That is a short name!";
}
?>
A page reload (used here), is necessary to send value to PHP as it is run server side. Your only other solution would be to use AJAX and load page content dynamically. This, however, would be the simplest solution.
EDIT:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var urlvariable = getUrlVars()['variableName'];
I am trying to return my SQL query array into a javascript array and then display the info one at a time. I have found a few helpful posts already on here but I still cannot get it to work. I am new to ajax and so please forgive any stupid mistakes. Below is the php followed by a description.
php: this is in an external file from index.php
<?php
include('connection.php');
$query = "SELECT * FROM photos";
$queryresult = mysql_query($query);
while ( $line = mysql_fetch_array($result) ) {
$path[] = $row[0];
}
$paths = json_encode($path);
header('Content-type: application/json');
echo $paths;
?>
This gets the results (they are file paths) array and json encodes them to pass to javascript. Connection.php is correct and it is working.
HTML/Javascript:
<html>
<head>
<script src="JavaScript/gjs.js" type="text/javascript"></script>
<script src="jquery/jquery-1.4.3.min.js" type="text/javascript"></script>
<script>
function imageload(){
var i = 1;
$.getJSON('phpfiles/getpiccode.php', function(data) {
var can = document.getElementById('canvas').getContext('2d');
$.each(data,function(idx, row){
var img = new Image();
img.onload = function(){
can.drawImage(img, 0, 0, 1280, 800);
}
img.src = row;
i++;
});
});
}
</script>
</head>
<body>
<div class="container">
<canvas id="canvas" class="canvas-one" width="1280" height="800">
<script>imageload();</script>This text is displayed if your browser does not support HTML5 Canvas</canvas>
</div>
</body>
</html>
I hope that makes sense. Thanks again!
Use json_encode() to encode it as JSON.
In recent browsers you can simply turn the string from that function into a JavaScript object using var obj = JSON.parse(yourstring); - but better use e.g. jQuery for AJAX and JSON parsing.
Update: Your JavaScript should looke like that to iterate over the data from your query:
$.getJSON('phpfiles/getpiccode.php', function(data) {
// get canvas object. it's the same for all images so only do it once
var can = document.getElementById('canvas').getContext('2d');
// iterate over the elements in data
$.each(data, function(idx, row) {
var img = new Image();
img.onload = function() {
can.drawImage(img, 0, 0, 1280, 800);
}
img.src = row;
});
});
However, it might not do what you want: It will draw all images pretty much at once at the same position.
Also replace <script>imageload() </script> (assuming that's the function containing your JavaScript) with <script type="text/javascript">imageload();</script> as that's the correct/proper syntax.
In your PHP code you'll have to replace return $paths; with echo $paths; unless you are using some framework which relies on your file returning something. Additionally it'd be good to send a JSON header: header('Content-type: application/json');
PS: SELECT * combined with MYSQL_NUM is a BadThing. It relies on the columns in the table having a certain order. If you just need one column use "SELECT columnName"; if you need all, use MYSQL_ASSOC to get an associative array.