Inserting PHP variable value in Javascript file - php

I have a JavaScript file which has a hard coded BASEURL variable, this value is then used by other functions in the file.
I would like for this url value to be set dynamically so that I don't need to manually change it for different installs. Is it possible to insert a PHP variable value into a JavaScript file?

Rather than try to mix PHP into javascript files, here's what I do in the HTML template:
<head>
<script>
var BASEURL = "<?php echo base_url(); ?>";
</script>
<script src="/path/to/my_script1.js"></script>
<script src="/path/to/my_script2.js"></script>
</head>
This sets the variable and allows all your embedded scripts to access it. base_url() would be replaced by whatever method you use to fetch the base url with PHP.

Suppose you have a JS file written on the fly by PHP; file1.php
<?php
header('Content-Type: application/javascript');
$var = $_GET['var1'];
echo "jsvar = ".$var.";";
?>
The client-side source code of file1.php?var1=10 will then be
jsvar=10;

There exists several ways:
Load the baseurl via AJAX, but maybe this is to slow, maybe you need it earlier.
let the javascript file running through the php parser. Then you could use inline echos.
The most convenient and easiest way, is to make a <script>var baseurl = '...';</script> in the html/php output of your page.

You will need to make your file a php file, not a js file. From there you can include any PHP tags in the file to work your dynamic magic. The key to make this whole thing work is in the headers, which you will need to set like so:
<?php
Header("content-type: application/x-javascript");
echo 'var js_var = ' . $php_var;
?>
alert (js_var);
This technique can be used to for CSS files as well.

Heredoc worked for me today:
<?php
echo <<<ANYNAME
<script LANGUAGE="JavaScript" type="text/javascript">
<!--
// code ...
var myLatlng = new google.maps.LatLng($lat, $lon);
// code cont. ...
//-->
</script>
ANYNAME;
?>
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
php variable in html no other way then: <?php echo $var; ?>

Related

how to declare dynamic JS variables for a PHP page

I'd like advice on the best way to include dynamic js variables. There are certain js variables which come from the server, similar to:
var user_preferences = [<?php //declare some type of array here;?>];
Obviously, you can't run PHP in a *.js file (though I suppose you could with Apache and a .htaccess directive), and besides I believe you don't want dynamic content in a *.js file because the whole idea is for the browser to cache the code.
The total set of these variables (such as AJAX url locations, user settings) is actually pretty small. I really would prefer not to declare them all on a page, but instead include them somewhere, but how would I do that given that they are dynamic?
As guys in comments said, you can run php in js files, just rename it.
Example of JS file, named generated_data.php:
function pero( miki ) {
miki.innerHTML = "<?php echo $_SERVER['DOCUMENT_ROOT']; ?>";
console.log("ext");
}
now, let us add this to html:
<html>
<head>
<script src="generated_data.php"></script>
</head>
<body>
<div id="test"></div>
<script>
pero( document.getElementById("test") );
</script>
</body>
</html>
You're close. All this in one file
<?php
$someCoolVar = "[1,2,3,4,5]";
// ...
?>
//.....
<script>
var myVar1 = <?=$someCoolVar;?>; // myVar1 = [1,2,3,4,5];
// ...
</script>

import php variables in javascript [duplicate]

This question already has answers here:
What is the safest way of passing arguments from server-side PHP to client-side JavaScript [duplicate]
(5 answers)
Closed 9 years ago.
I have a file called english.php containing a tonne of variable values. All part of the $LANG array.
Examples:
$LANG['value_1']="abc";
$LANG['value_2']="xyz";
I then have a million different .php files that use require_once('english.php');
That is fine but I also have a lot of javascript and jquery plugins that I am using. They all have external .js files. How can I get the values of $LANG in javascript to it is usable in the .js files?
I guess I am gonna need to add code to the top of the .js to somehow reading the .php data before running the remainder of the javascript code. I just have absolutely no idea how to do that.
I have seen a few possible ideas but I don't really want to do a major rewrite of everything. Looking for a simple solution. Can anyone help this clueless novice?
======= Added more info based on comments received =======
I now have a lang.php with this code in it...
<?php
session_cache_limiter('nocache');
session_start();
require_once ($_SESSION['language'].'.php');
$js_out = json_encode($LANG);
?>
<script>
var LANG = <?php echo $js_out; ?>;
alert(LANG.value_1);
</script>
When I access the lang.php it successfully accesses english.php and alerts 'abc'
My problem is that this does not work when added to a different file...
<script type='text/javascript' src='lang.php'></script>
<script>
alert(LANG.value_1);
</script>
======= Edited to add the SOLUTION =======
Thanks to the comments of the people below, I got rid of the <script> in the lang.php file and it worked.
I now have a lang.php with this code in it...
<?php
session_cache_limiter('nocache');
session_start();
require_once ($_SESSION['language'].'.php');
$js_out = json_encode($LANG);
?>
var LANG = <?php echo $js_out; ?>;
You can have the following code inside english.php:
<?php
$LANG['value_1']="abc";
$LANG['value_2']="xyz";
$js_out = json_encode($LANG);
?>
<script>
var LANG = <?php echo $js_out; ?>;
</script>
LANG is then visible to your javascript after the page loads.
you can do that with a simple script tag in the files which need to see the $LANG in javascript.
1) Create a php file which echoes the javascript representation of $LANG - lets call it lang.php
it should do something like
echo 'var english ="' . $LANG['value_1'] "';";
2) include this file in your html and then u can use the variables english etc. as normal javascript variables.
<script language="javascript" src="http://whatever.com/lang.php"> </script>
Try:
<script ...>
var mydata = <?=json_encode($LANG)?>;
</script>
json_encode returns a string containing the JSON representation.
http://php.net/manual/en/function.json-encode.php
I think the right thing to do is something like :
var foo = "<? echo $LANG['bar']; ?>";
The less php code you write in a js code, the better and cleaner it is.
You can create a PHP file:
<?php
header('Content-Type: text/javascript');
echo 'var lang = {};';
foreach ($LANG as $key => $value) {
echo "lang['$key'] = '" . addslashes($value) . "';";
}
?>
then link the script and you can use the lang object:
<script type='text/javascript' src='/path/to/lang.php'></script>
<script type='text/javascript'>
alert(lang.value_1);
</script>
Remove the <script></script> tags which possibly cause syntax errors when linked as a text/javascript file.

How to get value from php javascript?

I have a file php javascript
in news.js
news_id = 1;
document.write('<div id="news-id"></div>');
function output(strHtml) {
document.getElementById('news-id').innerHTML = strHtml;
}
in news.php is using
<?php
$news_id =
?>
news_id
<?php
$str = '<p>This is id: </p>'.$news_id;
?>
output(<?php echo json_encode($str); ?>);
And index.html i call
<script src="news.js" type="text/javascript"></script>
<script src="news.php" type="text/javascript"></script>
When i run index.html is error, how to get news_id from js to using in php
Well, as wrong as the original question is, there is a way to get the a JS variable into a PHP file.
In the HTML:
<script src="news.js"></script>
<script>
document.write('<scr'+'ipt type="text/javascript" src="news.php?myvar='+myvar+'" ></scr'+'ipt>');
</script>
In news.js:
var myvar = "HELLO";
In news.php:
alert("<?php echo $_GET["myvar"]?>");
Again, I highly discourage this approach... but it works.
You can't call news.php like this. It should be included in the html file like this:
include("news.php");
and you should change the extension of your html file to .php
To use PHP as javascript source <script src="news.php"
you need explicit declare content-type in .php
<?php header("Content-type: text/javascript"); //at very first line no white-space before ?>
//this is javascript content..
Important!
first, PHP execute on web server and send response to client(browser).
then javascript execute later in web browser.
To use js value inside php function you need AJAX GET/POST.

php tags in .js file

How do I enter a <? echo "hello"; ?> in a .js file.
This is a jquery app, therefore the js file.
Thanks
Jean
You would only be able to do this if the PHP interpreter is configured to run on *.js files, which by default it won't be. Quite honestly, I wouldn't recommend this behavior.
What I'd do instead is something like this (This method can be used for CSS files, too.):
<script type="text/javascript" src="js.php"></script>
js.php
<?php
//GZIP the file and set the JavaScript header
ob_start("ob_gzhandler");
header("Content-type: text/javascript");
//Set a JavaScript variable based on PHP work
echo 'var logged_in_user = "'.$_SESSION['username'].'";';
//Require an external script
require_once($_SERVER['DOCUMENT_ROOT']."/path/to/jquery.js");
?>
//More Javascript functions and code here
$(document).ready(function() {
$('#mydiv').tipsy();
});
<?php
//Flush the output buffer
ob_end_flush();
?>
I personally do this for many reason.
I have many jQuery files I want to include, but I don't want my browser doing 5+ HTTP requests. Including them all in one file means less HTTP requests.
GZIP! I'm significantly reducing the size of the file be transferred and that speeds things up for the visitor.
It's a central location to add, remove, or modify my JavaScript for the whole site. I can even use $_GET checks to make certain scripts conditional based on how I wrote the <script> tag.
For example, <script type="text/javascript" src="js.php?var=1"></script>. I can then check $_GET['var'] within the js.php file.
You regularly don't use PHP within your JavaScript files. Javascript is a client-side language which is interpreterred in your web browser. PHP is run on the web server.
However, if you need to pass data from your PHP-code to your javascript document, you can do something like:
$js = "<script> myObject = " . json_encode($your_data) . " </script>";
print $js;
If you do this in your <head>-part of your HTML-document, you will have access to myObject in other JS files you load after that.
$your_data can be an array or any kind of object, string or integer. Look for PHP JSON around the interwebs.
I think is not possible to enter a php in the js file, but:
try to create an element div for example or an input ...
and then use this functions to get the value of the div tag.
function AddHiddenValue(oForm) {
var strValue = document.getElementById("city").value;
alert("value: " + strValue);
var oHidden = document.createElement("input");
oHidden.name = "printthisinput";
oHidden.value = strValue;
oForm.appendChild(oHidden);
}
It come from another object form (select .. )
document.getElementById("city").value;
Ok guys here is the answer
The Q: I want to input a value for a variable into a .js file, php tags are not permitted and the js would throw an error.
The A: write a
<script> <? var value_pass = echo "hello"; ?> </script> before the said .js file
In the said .js file
var value=value_pass;
So there is no need to have any of the ob_end_flush.
If this is not viable please let me know.
Thanks
Jean

Access PHP var from external javascript file

I can access a PHP var with Javascript like this:
<?php
$fruit = "apple";
$color = "red";
?>
<script type="text/javascript">
alert("fruit: " + "<?php echo $fruit; ?>"); // or shortcut "<?= $fruit ?>"
</script>
But what if I want to use an external JS file:
<script type="text/javascript" src="externaljs.js"></script>
externaljs.js:
alert("color: " + "<?php echo $color; ?>");
You don't really access it, you insert it into the javascript code when you serve the page.
However if your other javascript isn't from an external source you can do something like:
<?php
$color = "Red";
?>
<script type="text/javascript">var color = "<?= $color ?>";</script>
<script type="text/javascript" src="file.js"></script>
and then in the file.js use color like so:
alert("color: " + color);
You can also access data from php script in Javascript (I'll use jQuery here) like this
Create input hidden field within you php file like this
<input type="hidden" id="myPhpValue" value="<?php echo $myPhpValue ?>" />
in your javascript file:
var myPhpValue = $("#myPhpValue").val();
//From here you can the whaterver you like with you js Value
if(myPhpValue != ''){
//Do something here
}
This will do the job as well :)
What I've seen done is let .js files run through the php interpreter. Which I can not recommend.
What I do recommend is fetching the values through AJAX and have the PHP file return the value to the JS file. Which is a much cleaner method.
First of all you have to understand that no program can actually have access to the other program's variable.
When you realize that, the rest is simple.
You can either set up a js variable in the main file and then include your external js, or make this external js dynamic, generated by PHP as well
What you likely want, is called Asynchronous JavaScript and XML (AJAX): http://www.w3schools.com/ajax/default.aspa
Basically, imagine being able to send messages from the clients JavaScript to your PHP scripts on the server. In the example you gave (externaljs.js), you would have the script ask the server what $color is, via HTTP. You can also point the script tag at a PHP script that generates the JavaScript you want. It depends on what you need to do.
It helps to have some understanding of taint checking, data verification, and security ;)
As the others are saying, javascript doesn't have access to php variables. However, it does have access to the DOM. So, you can use php to add attributes to some page element. And then you can access those attributes with javascript.
e.g. <div id='apple' class='red'> is completely available to javascript
Don solution is good, furthermore if you want to use a php array in an external javascipt this can help you:
PHP:
<?php
$my_php_array = [];
?>
HTML:
<script type="text/javascript"> var my_js_array = <?php echo json_encode($my_php_array);?> ; </script>
<script src = "../public/js/my-external-js.js"></script>
Javasript: (You can now use the array like a normal Javascript array)
my_js_array[0]
my_js_array.length
externaljs.js is a static file. Of course it can't access PHP data. The only way to pass PHP data to a js file would be to physically alter the file by writing to it in your PHP script, although this is a messy solution at best.
Edit in response to Ólafur Waage's answer: I guess writing to the js file isn't the only way. Passing the js through the PHP interpreter never crossed my mind (for good reason).
<script type="text/javascript" src="externaljs.js"></script>
You could change it to
<script type="text/javascript" src="externaljs.php"></script>
And the PHP script could just write JavaScript like that :
<?php
$fruit = "apple";
echo 'var fruit = '.json_encode($fruit);
...
Though using AJAX like said Sepehr Lajevardi would be much cleaner
2017-2018 and above solution:
Since nobody bringed it up yet and I guess no one thought of combining the functions base64_encode and json_encode yet, you could even send PHP Array variables like that:
index.php
<?php
$string = "hello";
$array = ['hi', 'how', 'are', 'you'];
$array = base64_encode(json_encode($array));
Then you could just load your desired js file with the parameter for a query string like this:
echo '<script type="text/javascript" src="js/main.php?string='.$string.'&array='.$array.'">';
Then js/main.php will look like this for example. You can test your variables this way:
js/main.php
<?php
if ($_GET['string']) {
$a = $_GET['string'];
}
if ($_GET['array']) {
$b = $_GET['array'];
}
$b = json_decode(base64_decode($b));
echo 'alert("String $a: + '.$a.'");';
echo 'alert("First key of Array $array: + '.$b[0].'");';
exit();
?>
The following will then output when you open your index.php. So you see, you don't open js/main.php and you still got the javascript functionality from it.
You can include() them just as you would anything else:
<?php
$fruit = "apple";
$color = "red";
?>
<script type="text/javascript">
<?php include('/path/to/your/externaljs.js'); ?>
</script>
This will basically render the external file as inline js. The main disadvantage here is that you lose the potential performance benefit of browser caching. On the other hand, it's much easier than re-declaring your php variables in javascript.
You cant do that and dont try to as this is not a recommended approach, However you can pass php variables as a function parameters to function written in external js

Categories