passing php variables to javascript - need help

Status
Not open for further replies.

reedjasonf

Solid State Member
Messages
9
I have 2 different files: vars.php and functions.js.

Inside my vars.php I have declared a few variables:
example:
$var1 = "This is a string";
$var2 = 50;
$var['array'] = "This is an array";

I'd like to pass these variables to my functions.js so that if I ever need to change the variables I only need to do that in the php file containing all my variables.

I've looked at other forums and they say I should be able to do this:

var jsvar = "<?php echo $var1;?>";
... but when I do this jsvar becomes literally "<?php echo $var1;?>" instead of "This is a string" like I want it to. Anyone know what my problem is?
 
Oh, I forgot to say that I've already used <?php include('vars.php'); ?> in my javascript file.
 
You cannot directly share variables between server and client like this. Your method won't work because even if php was running on the client system through the browser it wouldn't be, for lack of a better word, the same "instance" that is running on the server
 
this person should be able to to echo out strings in the php script for use in the javascript code.

data could then be "posted" back to the script via a webform.


it seems their php isnt parsing correctly.
 
Code:
<?php

$var1 = "This is a string";
$var2 = 50;
$var['array'] = "This is an array";

echo '<script type="text/javascript">var jsvar=' . $var1 . '</script>';

?>

This should work.
 
this person should be able to to echo out strings in the php script for use in the javascript code.

data could then be "posted" back to the script via a webform.


it seems their php isnt parsing correctly.

You can echo js out of a php script, yes, but look at the code he has posted. He is putting php into a js string variable... the js will be able to use that string variable on the client but the client won't then be able to "run" the php as if it were on the server.
 
in my mind, they are trying to duplicate a variable in php to a variable in javascript.

I agree that the php code will not run client side.

the jsvar line should be in the php script
 
Status
Not open for further replies.
Back
Top Bottom