Page 1 of 1

How do you insert a php variable in javascript

Posted: Sat Jan 13, 2007 5:57 pm
by PhinCuddy
(excuse me if what i'm asking sounds muddled)

i have a variable in php ....

Code: Select all

$varpab = <absolute_reference_to_website>
my question is, how can i use that same variable in a .js file (which houses my dropdown menu)? currently, in php when i link to a page i type

Code: Select all

<a class=\"nav\" href=\"".$varpab."directoryname/page.php\">


I would love to be able to use the same syntax in my js file.


hope that made sense..thanks for your help!

Posted: Sat Jan 13, 2007 6:00 pm
by Luke
PHP is interpreted on the server. Long before javascript is interpreted on the client's browser, so echo out the variable into the html.

Code: Select all

<a class="nav" href="<?php echo $varpab; ?>directoryname/page.php">

Posted: Sat Jan 13, 2007 6:09 pm
by PhinCuddy
that was fast...hey, thanks so much for that..off to try it now

Posted: Sat Jan 13, 2007 7:31 pm
by Ollie Saunders
To process JavaScript server-side add .php to the end of the file:

Code: Select all

important.js => important.js.php
Then you can just PHP inline in the JS file as you need. You should send the correct Content-Type header first though. Here's an example:

Code: Select all

<?php
header('Content-Type: text/javascript');
$foo = 2343;
?>
// This here be ye JavaScript ...yarrr 
var foo = '<?php echo $foo; ?>';
If the variable you are echoing from PHP:
  • came from the user e.g. via a form
  • came from the database
  • you know it has quotes in it
  • you don't know exactly what is in it
...thenyou should escape the quotes. With addslashes() (I believe this is sufficent for JavaScript. This will prevent XSS security vulnerabilities. Example:

Code: Select all

<?php
header('Content-Type: text/javascript');
$unknown = $_POST['data'];
?>
var foo = '<?php echo addslashes($unknown); ?>';