views:

352

answers:

5

I am trying to figure out how to set my session_id variable to to be used in an external js file. Here is what I have.

php file:

$output = '<script src="test.js">
     var session_id = '.$_SESSION['id'].'
</script>';
print $output;

js file:

alert(session_id);

With this I am getting an error saying session_id is not defined. Is there a way to pass this info across?

I know I could just setup a hidden input with the info but I am thinking there is a better way of doing it.

+2  A: 

Hum, what about:

$output = '<script type="text/javascript> var session_id = '.$_SESSION['id'].'</script><script type="text/javacript" src="test.js"></script>';
print $output;

?

Enrico Carlesso
Small typo: remove the "." behind $_SESION['id'] and use $_SESSION['id'] instead of $_SESION['id'] ;)
Select0r
Woops. Thanks for notice!
Enrico Carlesso
A: 

The content within the <script> tag is only executed if the JavaScript file is not found. Set your variables in a separate <script> tag before that has no file set:

<script>
     var session_id = '<?=$_SESSION['id']?>';
</script>
<script src="test.js">
</script>
Ignacio Vazquez-Abrams
+1  A: 

If you can deal with session_id as a global variable, then the following will do it:

<script>
     var session_id = '<?php echo $_SESSION['id'];?>'
</script>
<script src="test.js"></script>

If you want to make the variable only available to the javascript file in a closure etc. you can send the js file through the PHP parser or use parameters for your js file, but the latter is not really easily accessible from javascript, see my question about that.

Residuum
+1  A: 

If you're including an external JS file, you can't put code between the script tags. So you want:

<script type="text/javascript">
    var session_id = <?php print $_SESSION['id']; ?>;
</script>
<script type="text/javascript" src="test.js"></script>

Though you could get around this kludginess by making the session ID a hidden form field in your HTML and then using DOM methods in test.js to find it.

beamrider9
A: 

Another solution is to have PHP serve a script like this:

  • Have a JS file prepared with the variable definitions you require:
var value1 = '{value1}';
var value2 = '{value2}';

...
// script goes here
  • With PHP, read the file and replace the {value1} and {value2} tags with your data:

if ($_GET["script"])
{
 $data = array(
   "value1" => $_SESSION["id"],    # i.e.
   "value2" => $foo
 );

 $script = file_get_contents($script . ".js");

 foreach ($data as $key => $value)
 {
  $script = str_replace("{" . $key . "}", $value, $script);
 }

 header("Content-Type: text/javascript");
 echo $script;
 exit();
}
  • Then you can call your PHP "parser" like this:
<script type="text/javascript" src="?script=myscript"></script>
Joel Alejandro