1

Hello Stackoverflow Users,

I hope you can help, basically say I have a PHP File with a variable, lets say domain.com/forum/myname.php - In that myname.php file is:

$myname = "jake";

Now, I have a JS File at domain.com/forum/js/template.js

How would I get this PHP Variable into the JS File? I know once I have the PHP Variable I could do

var string = $myname;

and then use string wherever I want it to display, but the matter is how do I transfer it from PHP to the JS File?

I have seen other questions relating to this, but not one offers a clear explanation on how to do it?

Thanks.

2
  • 2
    You can set your variable $myname before calling external js file Commented May 20, 2014 at 12:54
  • use ajax and call from js and get it. Commented May 20, 2014 at 13:05

4 Answers 4

3

You would have to request your JS file through the PHP parser, and get PHP to output the correct content type text/javascript, then in your JS file you would do

var string = <?php echo $myname ?>;

or if you turn short_open_tags on then you can just do:

var string = <?= $myname ?>;
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

index.php

$var = "hello world";
<script>
var phpVar = "<?php echo $var; ?>";
</script>

<script src="jsfile.js"></script>

in your jsfile.js :

alert(phpVar);

Comments

0

declare myname variable as a global js variable. If you declare like this you can access any where in webpage files.

In myname.php file :

<script>
window.myname = <?php echo $myname;?> // declare as global variable
</script>

In Js File :

var myname = window.myname;

2 Comments

Hi Manibharathi, Thanks for your answer, however, when I try and show the var "myname" it comes up as undefined instead of showing the value
@user3615703 include the js file after declare the window.myname.
0

One approach I have taken in the past is something like this:

in my js:

var myVal;

function init(val) { myVal = val; }

in my php:

<script>
....
var theVal = "<?=$phpVal?>";
init(theVal);
</script>

1 Comment

Hi mrpotocnik, Same Again, I tried this and when I try to show the var "theVal" - its coming up as undefined :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.