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

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

Related

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.

How To Pass PHP Variable To This Javascript Function?

Let's say I have this PHP variables :
$SelectedCountry = "USA";
$SelectedState = "Texas";
on the other hand, I have this javascript function to display all available countries and states :
function print_country(country_id){
// given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(country_id);
option_str.length=0;
option_str.options[0] = new Option('Where do you live now?','');
option_str.selectedIndex = 0;
for (var i=0; i<country_arr.length; i++) {
option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
}
}
function print_state(state_id, state_index){
var option_str = document.getElementById(state_id);
option_str.length=0; // Fixed by Julian Woods
option_str.options[0] = new Option('Select state','');
option_str.selectedIndex = 0;
var state_arr = s_a[state_index].split("|");
for (var i=0; i<state_arr.length; i++) {
option_str.options[option_str.length] = new Option(state_arr[i],state_arr[i]);
}
}
my question is... how to make 'USA' and 'Texas' becomes selected <option> which generated by those two javascript functions? thanks.
NOTE #1 : you can see the complete code of javascript here : http://sourceforge.net/projects/countries/files/
NOTE #2 : those function called by adding this line on my PHP :
<script type="text/javascript" src="scripts/countries.js"></script>
<script language="javascript">print_country("country");</script>
so basically I need your help how to pass that PHP variables so that it can be 'received' by javascript function INSIDE that countries.js file.
One way is to just echo out some JavaScript statements:
<script>
<?php
echo "
var SelectedCountry = '$SelectedCountry';
var SelectedState = '$SelectedState';
";
?>
</script>
Then just use them in your loops to check if the option needs to be selected or not.
If you're going to be doing a lot of this sort of thing, though, embedding PHP into JavaScript isn't really the best approach. Read up on AJAX and PHP's json_encode() function.
There are two answers:
1 Use AJAX cal and pass back JSON
$.ajax({
url: '/myScript.php',
success: function(data) {
//Do something
}
});
myScript.php
return json_encode($myVar);
2 Embed PHP into the JavaScript
<script>
var myPHPVariable = <?php echo $myVar; ?>
</script>

How to pass value from javascript to php using address bar

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

Getting through the DOM from the file to which I did a post request through ajax

I used this simplify examples to explain better the question.
given the following post request under ajax:
$(document).ready(function()
{
$(#submit).click(function()
{
$var = $("#result");
$code = $("#code");
$.post("ajax.php", {option : $var, code: $code}, function()
{
//Getting through the DOM could be useful if you want to analyse the answer coming from the ajax.php file
var $DOMresponse = getElementByTagName("div")[0].firstChild.data; // I would want the correct code here because this is incorrect... this is ti give you an idea
if($DOMresponse == "your code is correct")
{
$("#container1").fadeOut(400, function(){ $("#container1").html(result); });
$("#container1").fadeIn();
}
elseif($DOMresponse == "your code is incorrect. Go again trough the procedure")
{
$("#container2").fadeOut(400, function(){ $("#container2").html(result); });
$("#container2").fadeIn();
}
// In this second case I could fill the second container id="container2"
});
});
});
ajax.php example:
<?php
if($_POST['request']==1)
{
if($_POST['code']==$user['code'])
{
?><img src="...">
<div>tomatoes</div>
<div>potatoes</div>
<div id="answer">your code is correct</div> <?php
}
else
{
?><img src="...">
<div>apples</div>
<div>oranges</div>
<div>your code is incorrect. Go again trough the procedure</div> <?php
}
}
I would like to know how to get through the DOM of the ajax.php file.
how do I do this? Thanks
Do you need to do this before inserting the result to the page? If so create new element and insert the result to it. For example
var div = document.createElement('div');
var obj = $(div).html(response);
Now you have a standard jQuery object with the dom element.
Responding to the comment:
I am confused. Do you want to validate the code in php or js? It looks like your checking if what is send through post is the same as defined in $user variable. So validating the code is done in php. In that case wouldn't be simpler to use json as a response. In php script create result array with key status set to 1 or 0. In post resposne you can check response.status == 0.
Other wise it look just strange that you make the validation once in php and the twice in js after response. Besides if you set your response to be standard text then you have to create dom element and place the reponse inside to be able to search through it.
I think what you're asking is how do you get the value of $('#code') in the ajax.php file.
Here's what you're doing:
var $code = $('#code'); // jQuery object
$.post('ajax.php', { code: $code });
The problem with this is that you're passing the entire jQuery object to ajax.php. What you probably want to do is pass the value or html of the $('#code') object, like so:
var code = $('#code').html(); // if it's a non-input element
var code = $('#code').val(); // if it's an input
$.post('ajax.php', { code: code });
Then in the ajax.php file, your $_POST['code'] will equal the value of code (e.g. "ABC123"), which you can then use to compare with $user['code'] or whatever you want.
I hope I understand the problem correctly. Good luck.
EDIT: I think I understand what you're getting at now. What you want to do is this:
HTML:
Javascript:
var $option = 'request';
var $code = $('#code').val();
$.post('ajax.php', { option: $option, code: $code }, function(data) {
if (data == 'valid') {
// show valid code result here
} else {
// show invalid code result here
}
});
and ajax.php
<? if ($_POST['option'] == 'request') {
if ($_POST['code'] == '123ABC') {
echo 'valid';
} else {
echo 'invalid';
}
}
?>
Notice that the variable data comes from the function(data) part in the $.post parameter. That data variable contains the response from ajax.php (in my example, it would be 'valid'.)

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