How do you insert a php variable in javascript

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
PhinCuddy
Forum Newbie
Posts: 7
Joined: Mon Jan 08, 2007 6:57 pm

How do you insert a php variable in javascript

Post 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!
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post 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">
User avatar
PhinCuddy
Forum Newbie
Posts: 7
Joined: Mon Jan 08, 2007 6:57 pm

Post by PhinCuddy »

that was fast...hey, thanks so much for that..off to try it now
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post 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); ?>';
Post Reply