How to pass value from javascript to php using address bar - php

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'];

Related

PHP: Read an html file and get access to JS variable

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
*/

AngularJS with PHP to get and update a link

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.

Angular.js > how to manage configuration

I got stuck with passing a configuration to our angular application. My problem is
We have configuration is stored in database, so far it's URL of web service to communicate with
Page is rendered by PHP
How can I pass URL stored in database to ng-app?
So far I have hard-coded services.js
app.constant('config', {ws_url: 'ws://domain/ws'});
app.factory('wampy', function ($rootScope, config) {
var url = config.ws_url;
var ws = new Wampy(url, { autoReconnect: true });
return {
something: function () {
console.log(url); // usage of url
}
}
}
Then it is included into main html code (index.php)
<head>
<script type="text/javascript" src="http://dev.local/js/ng/app.js"></script>
<script type="text/javascript" src="http://dev.local/js/ng/services.js"></script>
</head>
But it can be amended / moved to somewhere else.
Any thoughts?
You could have a snippet of javascript rendered by php into a script tag like so
$config = array('ws_url' => 'ws://domain/ws');
$jsonConfig = json_encode($config);
$snippet = <<<EOS
<script type="text/javascript">
angular.module('appName').constant('config', $jsonConfig);
</script>
EOS;
and then output this $snippet somewhere in your page.

JavaScript Redirection

Here is the code I have,
<script language="JavaScript">
var url = "http://localhost:8888/uploads/"+<? $name ?>+"/output.txt";
setTimeout("top.location.href = url",1000);
</script>
$name is a PHP variable which has the name of which directory I'm trying to redirect to.
Needless to say, it isn't working. What's wrong with it? I don't know a lot about javascript so I probably did something stupid
Thanks
If your mixing PHP with JavaScript, it's always advisable to check the output being sent to the browser: right click on your website and click view source!
JavaScript doesn't care whether the content being sent to it is static HTML, from a Database or generated by PHP. If its in the output, it'll parse it.
If you'd have done that, you'd notice that your not echo'ing the $name variable.
<script language="JavaScript">
var url = "http://localhost:8888/uploads/"+<? echo $name ?>+"/output.txt";
setTimeout("top.location.href = url",1000);
</script>
But that'd give you
<script language="JavaScript">
var url = "http://localhost:8888/uploads/"+ foo +"/output.txt";
setTimeout("top.location.href = url",1000);
</script>
Which isn't valid JavaScript, as foo is now a JS variable, not a string.
So you should have:
<script language="JavaScript">
var url = "http://localhost:8888/uploads/<? echo $name ?>/output.txt";
setTimeout("top.location.href = url",1000);
</script>
Furthermore, passing a string to setTimeout (or setInterval) is not recommend; for the same reasons against using eval(), so you should end up with something like this instead:
<script language="JavaScript">
var url = "http://localhost:8888/uploads/<? echo $name ?>/output.txt";
setTimeout(function () {
top.location.href = url
},1000);
</script>
Pass a function, not a string, to setTimeout.
var url = "http://localhost:8888/uploads/<?= $name ?>/output.txt";
setTimeout(function ()
{
top.location.href = url;
}, 1000);
I am assuming that the $name is properly filled in by PHP.
Try this:
setTimeout(function() { top.location.href = url; }, 1000);
Try like this:
var url = "http://localhost:8888/uploads/"+<? $name ?>+"/output.txt";
setTimeout(function() {
top.location.href = url;
}, 1000);
<?php echo "var url = 'http://localhost:8888/uploads/$name/output.txt'"; ?>
Remove pluses and braces - just put variable in url.
Also use Firebug to troubleshoot your JS code: http://getfirebug.com/
Use 'echo' or the slightly unreadable php short code <?= to echo out a variable.
<script language="JavaScript">
var url = "http://localhost:8888/uploads/<?php echo $name; ?>/output.txt";
setTimeout(function(){
top.location = url;
}, 1000);
</script>
I know I've created another closure, but feel it's more readable.
It should be:
window.location.href = url

Send php variables to flash using flashvars

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.

Categories