Getting another URL's Javascript variable in PHP? - php

I was wondering if there was some way to get a javascript variable from another url into a variable within PHP?
For example:
A page called exampleurl.com/page (which I do not have control over) with some inline javascript like:
function examplefunction() {
evar = "http://ikmp.co/Usdfio1";
}
Assuming there's HTML and other javascript surrounding this variable I want, how would I be able to retrieve it? Is there a special function to do this, or would it be easier to simply parse the HTML through PHP and then trim the variable to what I want?
In theory, the PHP would have a URL set to retrieve the JS from, and it would echo only what is in that variable.
PHP code (hypothetical) at mysite.com/getvariable.php:
$url = 'exampleurl.com/page';
$js_var = get_js_data($url, $evar);
echo $js_var;
Thanks in advance to anyone who can help me out here!

how about this:
HTML FILE:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<div id="result"></div>
<script>
var javascriptVar ='pie'; //this is whatever the js variable you want it to be
$('#result').load('path/to/my/myphpfile.php?var='+javascriptVar );
</script>
myphpfile.php
<?php
$javascriptVar =$_GET['var'];
echo $javascriptVar;
?>
notice the php code HAS to be in a seperate file than the html for this to work

Related

How call PHP from HTML to get url?

I am installing Disqus Comment system on my website. I understand that I can dynamically call the page url or id via php and thus do not need to hardcode the URL or page ID everytime I have a Discus comment box.
This question asked 7 years ago this answer was provided by #Yogus but I couldn't get it to work.
<HTML>
<title>HTML with PHP</title>
<body>
<h1>My Example</h1>
<?php
include 'testConnection.php';
?>
<b>Here is some more HTML</b>
<?php
//more php code
?>
</body>
</HTML>
I've hear that to use PHP I must change my website pages to end in .php rather than .html. I don't want to do this for every page as it would probably affect SEO and I've currently 325 pages.
I'd like to do a call to a PHP file, have it return a variable with the URL or Page ID and then I can plug this into the Discus. I've read there is a dedicated variable maybe $_SERVER which returns the page URL or ID.
Any help would be appreciated! Oh, a link to one page where I've Discus installed is here {go to bottom}. This page is hard coded in.
coinsandhistory.com/countries/Ancients_Rome/Ancients_48_Rome_Empire_Tetrarchy-Constantine.html
You can still keep your pages as HTML in this case.
You can make a call to the PHP page with Javascript, get the result via AJAX, and then use that result in a URL. In this example, I will feed the php a parameter that will determine what the URL will be. The HTML page will use javascript to populate the link in the anchor tag with the data coming from the php file.
example
the PHP code would look something like:
<?php
$p = $_REQUEST['p'];
if($p == 'one')
echo 'http://urlone.php';
if($p == 'two')
echo 'http://urltwo.php';
?>
the HTML code would look something like:
<html>
<script>
function populateURL(param){
//get the anchor tag
var link = document.getElementById('dlink');
//call the php file to return the url as a string,
//then set the url of the anchor to that string
fetch('url.php')
.then(response => (response){dlink.href = response});
}
//get the url if the value is 'one'
populateURL('one');
</script>
<body>
<a id="dlink">CLICK HERE </a>
</body>
</html>
I found a working answer on SO from ~10 years ago.
Get current URL with jQuery?
The solution was to use javascript from within the HTML which has queries for such things.
// Returns path only (/path/example.html)
var pathname = window.location.pathname;
// Returns full URL (https://example.com/path/example.html)
var url = window.location.href;
// Returns base URL (https://example.com)
var origin = window.location.origin;
To look at the results I just use the javascript to write out the answer, i.e
<p>JavaScript variables<br><br>
page url:
<script type="text/javascript"> document.write(page_url)
</script>
Thus php nor an external file wasn't needed. A note the javascript variable assigns MUST be done before the print commands, otherwise Chrome reports an error & nothing is displayed.

Using PHP variable and use it in Jquery/Ajax page load request

Let's say I have set up a PHP variable like this:
$phpurl = $_GET["url"]
where url value will be from GET variable query. The value of "url" will be some sort of html page link with some content like "myContent.html" I want to load.
How can I get this "url" value, which I have assigned to the variable "$phpurl"
and use it in the Ajax/Jquery page load request?
$('.content').load(' ** need the value of "$phpurl" to be placed here ** ');
Hope the question is clear. I am pretty new into programming. Thanks.
EDIT:
$('.content').load('<?php echo json_encode($phpurl); ?>');
will do
You'll want to take precaution to escape the value properly
<script type="text/javascript>
var url = decodeURIComponent('<?php echo rawurlencode($phpurl) ?>');
</script>
Or you could try something like https://github.com/allmarkedup/jQuery-URL-Parser
// requires no PHP at all!
var url = $.url(window.location).attr('url');
$('.content').load(url);
As a generic rule you should properly escape variables when you move them between two realms, in this case from PHP to JavaScript.
This is especially true if you don't have full control over the variable contents, such as those coming from $_GET, $_POST, etc.
This is a safe bet, using json_encode() to form a proper JavaScript value:
$('.content').load(<?php echo json_encode($phpurl); ?>);

Postpone execution of <script> in HTML - on user's request

I've got a block of PHP generated JavaScript code for WYSIWYG editor which looks like this:
<script>
code contains ', " etc.
</script>
As soon as this script appears on page, specific textarea is replaced by WYSIWYG. But I want to do this only when user asks for it. The problem is, I cannot get this JavaScript into PHP variable, because the editor's PHP method replace() echos the javascript right away.
So I want to put this <script> into a variable so that I could call it later when user requests it. Is it possible?
One solution came to my mind - put this <script> into external HTML file and load this file via AJAX.
Why not just have your script echo into a JS function, like this:
<script>
function enableWYSIWYG() {
// body of your code here
}
</script>
Then have a button that calls that function to enable the editor.
In php one can use output buffering to take any function that outputs text (and even text like this ?> TEXT <?php) and store it in a variable.
You'd do something like this:
ob_start();
replace(); // or whatever the function that generates the javascript is...
$script = ob_get_contents();
ob_end_clean();
In order to be able to call this later you could then do something like this:
$script = str_replace('<script>', '<script>function showEditor() {', $script);
$script = str_replace('</script>', '}</script>', $script);
echo $script;
This is rather hackish and could end you up in a lot of trouble later on especially if the called code changes), so I wouldn't be the one to recommend it. It may be the easiest way to do this, though.

is it possible to dynamically assign ID to an element in webpage using JS/ PHP?

can i set the id of an element programatically, as in a dynamic setting of id of an element, during runtime of the webpage?
Consider this scenario -
<body id="body1">
Now, i want to set the id of this element "body" dynamically, using the value of a variable in the php code. Is this possible? something like -
<body id=" <?php echo $bodyID; ?> ">
I use php and jquery in the page; please let me know whether such dynamic id assignment is possible to the elements in the html.
thanks.
PHP is the background language, it's what produces your HTML output. So basically, what ever you output from PHP eventually becomes your HTML, meaning yes you can use PHP variables as your elemnt-ID or anything else for that matter.
<?PHP
$var = "body1";
?>
<body id="<?PHP echo $var; ?>"> Hello my ID is <?PHP echo $var; ?></body>
OR You can output all of the HTML using a single echo statement.
<?PHP
$var = "body1";
echo "<body id='$var'>Hello my ID is $var</body>";
?>
In conclusion, whatever is left after PHP is finished executing is your HTML code that the end users browser interprets... Hope this helps...
$(function() {
var variable = 'insert_id';
$('body').attr('id', variable);
});
gives (with jquery)
<body id="insert_id">
Why not? As long as you keep your randomizer ( Math.rand ) big enough there should be little chance for conflicts.
I usually do this, and then at the same time call a JS method and passing the same ID. That would require you storing the ID aside so you can pass it later.
Edit: If you are only setting this on the body then you would not need to access it later.

What is the best practice to pass many server side information to JavaScript?

Let say that I have many Javascript inside pages. At this moment is pretty easy to initialize variable by simply using some Print/Echo statement to initialize JavaScript value.
Example: var x = <?php echo('This is a value');?>
I first thought that I could pass all variables value by parameter of function BUT it's impossible because we have a lot of values (we have a multilanguage website and all text are from the server (BD)).
Example : initializeValues(<?php echo('Value1,Value2,Value3,Value...');?>);//JS Method that can be external of the page
More problem come when we want to take off all JavaScript from pages to move everything on external JavaScript file. What would be the good way to initialize all those variables? If I bind the JavaScript methods by using OnLoad of the document I won't be able to use Print/Echo method to populate all values.
Any good pattern to resolve this task?
A very popular pattern is the use of the JSON format. There are libraries to produce it, and Javascript directly consumes it.
With php you can create an associative array then using json_encode you can serialize it for output on the page between some script tags.
for some examples on doing that you can look at http://www.php.net/manual/en/function.json-encode.php
Here's how I do it:
<?php
$foo = array('bar' => 'gork');
?>
<input id='foo' type='hidden' value='&lt?= json_encode($foo); ?>' />
Then client side (I'm using Prototype) :
var foo = $F('foo').jsonParse();
alert(foo.bar);
var x = <?php echo('This is a value');?>
Er, no, that would end up as:
var x = This is a value
(syntax error.) You want:
var x = <?php echo json_encode('This is a value', JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT);?>
The HEX_TAG escaping in PHP 5.3 avoids problems with the </ sequence appearing in a <script> block. The AMP and QUOT encoding is needed to ensure there are no problem " and & characters when you're putting code in an attribute value delimited by " or a non-CDATA XHTML script block. If you're only ever using a HTML script block (or XHTML CDATA script block) you can get away without them (although they do no harm either).
json_encode will also happily encode an array of values to put in a JS variable, not just a string.
More problem come when we want to take off all JavaScript from pages to move everything on external JavaScript file.
It's a good idea to put all your static code, including code that binds onto event listeners, in an external JavaScript file. However per-page data should still stay on the page, either in appropriate attributes of the document itself (eg. class names for unobtrusive scripting) or in a simple <script type="text/javascript">var data= ...;</script> block with no other code.
best practice? passing values from server to the client-side js is too volatile for a singular best practice.
let's say you use Smarty. then, my best practice is:
<script type="text/javascript">
var limit = Number("{$limit}");
var msg = "{$msg}";
{literal}
// code using the variables
{/literal}
</script>
but I can also see this as a very sensible approach:
function to_js_vars(arrray $jsvars)
{
foreach ($jsvars as $name => $info) {
printf(
"var %s = %s("%s");\n"
, $name
, $info['type']
, $info['val']
);
}
}
where $info['type'] is one of Number, Boolean, and '' (empty string) for everything else

Categories