Getting PHP variable in Javascript code - javascript

I'm trying to use PHP variables in Javascript but I couldn't. After over 2000 lines of writing different JS functions I was fine avoiding that but now I really needed it. I'm a bit lost on all the ways to go about this but nothing really worked. Here is my sequence:
index.html file:
...
<script src="myfunctions.js" />
....
myfunctions.js file:
....
function test() {
var x = <?php echo $_conf['user_id'];?>
console.log(x);
}
I was trying to rename the .js file into .php file and add
header("Content-type: text/javascript");
at the beginning - that didn't work. I was trying to make .htaccess file with
AddType application/x-httpd-php .js
But that didn't work either. I'm probably missing just a tiny thing. I just need someone fresh and bright to point it out.

You can do something like this within your JS code.
var php_var = "<?php echo $_conf['user_id'];?>"

Your javascript file should be named as "javascript.php" (just put the name you want, the only important thing is the .php
You have an index.php
Write in your index.php
include("javascript.php");
Then in your javascript.php
<script>
function test(){
var variable = "<? echo $conf['user_id'] ?>";
alert(variable);
}
<script>
PS: Yo don't need any header.

Since you're doing this via a <script> tag, your PHP script MUST output valid Javascript code, as if you'd literally type your variable assignment in manually. That means doing something like:
HTML/JS:
<script src="myscript.php"></script>
PHP:
<?php
$myvar = 'foo';
?>
var myvar = <?php echo json_encode($myvar); ?>;
Which in the end, will produce somethign that will function exactly as if you'd manually typed in the following:
<script>
var myvar = 'foo';
</script>
Note the use of json_encode(). Using this ensures that whatever you're outputting from PHP will become syntactically valid Javascript.

You're not assigning PHP value to a Javascript variable. Try:
var v = "<?php echo $_conf['user_id'];?>";

index.html
..
<script src="myfunctions.js.php" />
...
myfunctions.js.php
<?php
header('Content-Type: text/javascript');
...
?>
var val = <?php echo json_encode($val); ?>;
...

Other possible solution is to assign server-side data to attributes in html and read them in javascript. For example index.html could contain something like this:
<div id="user-profile" data-user-id="<?php echo $conf['user_id']; ?>"></div>
and in js file you can get them while necessary(example with jQuery):
var userID = $('#user-profile').attr('data-user-id');
Of course you should adjust your server-side settings to process html files.

Related

Doxygen php with embedded javascript

I use doxygen to document PHP-code and Javscript-code. That works great for plain language files, but not for main-web-php files containing embedded Javascript. Several options I have tried but none is working correctly. Have anyone a splendid idea?
Simplified example code:
<?php
$str = "How do I process embedded Javascript in doxygen";
?>
<script type="text/javascript">
// These construct needs a php-file extension.
// This is just an example it is used within javascript functions also.
var str = <?php echo json_encode($str); ?>;
/**
Doxygen does not process this Javascript function.
*/
function hello() {
echo "Hello world";
}
</script>

loaded js works different to hardcoded

I have the following script that works perfect.
<script type="text/javascript">
$(document).ready(function() {
php_test();
});
</script>
<script type="text/javascript">
function php_test() {
alert('<?php echo(DIR); ?>myfile');
}
</script>
The output is as expected:
http://localhost/mvc_framework/myfile
when I put the function php_test in a file lets say ‘php_test.js’ and bind it to my footer it executes with this output:
<?php echo(DIR); ?>myfile
Any explanation? Im confused…
The way you asked the question makes it confusing. It is possible to make PHP run on all types of files on your server with a bit of Apache tweaking. My solution will make your JS files be processed by the PHP interpreter.
What you need to do is create a .htaccess file if you are using Apache. I am going to assume you are. Then you add this line into it:
AddType application/x-httpd-php .php .js
The above code will force the PHP interpreter to run on all the formats listed in the command. You can also add .htm or even .css if you need PHP to do something with those files on the server side.
Refer to this question here for a previous solution to similar question > Using .htaccess to make all .html pages to run as .php files?
Or you can just store a whole bunch of variables from the PHP end on the page as Javascript variables like this example from one of my projects:
<script type="text/javascript">
var trackFilterFlag = null;
<?php
echo "trackFilterFlag = \"". $displayedPageType ."\";\r\n";
?>
var trackFilterCategory = null;
<?php
if(strcmp($displayedPageType, "mood") === 0 || strcmp($displayedPageType, "genre") === 0) {
echo "trackFilterCategory = \"". $filterCategory ."\";\r\n";
}
?>
var sortingTracksBy = null;
<?php
if( isset($chosenSortFlag) && strlen($chosenSortFlag) > 3 && !($defaultSort) ) {
echo "sortingTracksBy = \"". $chosenSortFlag ."\";\r\n";
}
?>
</script>
Of course I was still a novice when I wrote that code, it's possible to make it much neater and just make PHP echo the whole thing, but you understand what I mean :)

How to write JSON code from PHP in JavaScript file

This is my employeeshift.js code and I can't figure out how to do a PHP code in a JavaScript file
This is my code inside the employeeshift.js but my var inorno is null
$(document).ready(function(){
var inorno= "<?php echo json_encode($inOrOut ); ?>";
if(inorno=="0"){
$('.Sales1').hide();
}else{
$('.Sales1').show();
}
});
Rename your js file to php ....or past js code to php file then do like below
<?php
//some of your main php file code ..........
?>
<script type="text//javascript">
$(document).ready(function(){
var inorno= "<?php echo json_encode($inOrOut ); ?>";
if(inorno=="0"){
$('.Sales1').hide();
}else{
$('.Sales1').show();
}
});
</script>
Your JS file is probably NOT parsed as PHP script, unless you changed some server config. One way would be to rename it to employeeshift.js.php
if this is your JS file than var value will always be null, you can assign value to a var only when the file is php and you are adding this in script tag
You can't (and probably shouldn't, even if you could) write PHP into a JavaScript file. PHP on your server doesn't "know" that it should execute any PHP code you've placed there. An alternative would be to put the JavaScript, surrounded by <script></script> tags, in a PHP file, and then your could should work.

Passing a PHP variable into a Javascript function

I have a PHP variable that I am declaring upon loading the page, and want to use it in a JavaScript/jQuery function that loads upon a button click.
I have the following on my index.php page:
// Creating a random name for a file and creating it. Working properly.
$fname = substr(md5(rand()), 0, 7);
$file = fopen("temp/" .$fname, 'w');
And when I click a button, the following JavaScript function should run:
//Use the generated filename in the JavaScript function
var fname = <?php echo $fname; ?>;
var fileName = "temp/" + fname;
My understanding is that the PHP variable is outside of the scope of the JavaScript function, since I believe this is the way it should be done.
Can you please help with this?
PHP generates a page and presents it to a browser. As far as the browser is concerned, by the time the page is received, PHP is finished. So to answer your question, that should work, since PHP will essentially just spit out the text on to the page, which will act as normal. That is, unless I am terribly misinformed.
The "scope" of a PHP variable is long gone by the time Javascript gets to run, so that isn't really an issue.
Try do this. in a php file of course.
var fname = '<?php echo $fname; ?>';
I think you need an extension on your filename:
$extension = ".txt";
$fname = substr(md5(rand()), 0, 7).$extension;
$file = fopen("temp/" .$fname, 'w');
The problem is the missing apostroph like anant kumar singh mentioned.
I tested the following code in a webpage:
<?php
$fname = substr(md5(rand()), 0, 7);
$file = fopen("temp/" .$fname, 'w');
?>
<html>
<head
</head>
<body>
<script>
var fname = "<?php echo $fname; ?>";
var fileName = "temp/" + fname;
</script>
</body>
</html>

Calling Javascript function in an external file through php file?

Javascript code (In another file in the same directory):
function js(str)
{
alert(str);
}
PHP code(in current file):
<?php
echo '<script type="text/javascript" src="C:\xampp2\htdocs\ARD\call_jsfunc_diff_page.js"> </script>';
echo '<script>js("hello!!")</script>';
?>
I have checked on many links on the internet, i think i'm doing the right way, but the javascript function js(str) doesn't get called !!
Can somebody help me please ??
Before you edited the question: You called the function js but you are trying to call the func function.
Access to local hard disks is also problematic. Use a relative URI and access the .js over HTTP instead.

Categories