Forum Moderators: coopster

Message Too Old, No Replies

Session variables do not pass into a javascript include

         

cameraguy

11:04 pm on Jul 16, 2005 (gmt 0)

10+ Year Member



I am having a bad day! I was however able to narrow down my problem to this:

Assuming my session variable $_SESSION["logged"] is properly set to "yes", the script in page1.php will display "yes" only once:

page1.php
---------
<? session_start();?>
<html>
<body>
<? echo $_SESSION["logged"]?>
<script language="javascript" src="http://page2.php"> </script>
</body>
</html>

page2.php
---------
<?
session_start();
<? echo $_SESSION["logged"]?>
?>

Called directly, page2.php will display "yes", but called through the js include of page1, it will not.

And that is my mystery of the day!

StupidScript

9:37 pm on Jul 18, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The JS file is only triggered at the client end ... and PHP is activated at the server, before the page is delivered to the client ... and a PHP session is not naturally available to JS, as they are completely different technologies that don't speak each other's languages ...

Use PHP to pull the PHP session variable and write it's value into a Javascript variable on the page:

<?

if (isset($_SESSION["logged"])) {

echo "<script type='text/javascript'>sesslogged=".$_SESSION["logged"].";</script>";

}

?>

THEN it will be available to Javascript, either to an included script or to a script on the page following the variable value assignment.

mcibor

9:00 am on Jul 19, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I think it's enough to pass the session id to javascript and then use it.

page1.php

<? session_start();?>
<html>
<body>
<? echo $_SESSION["logged"]?>
<script language="javascript" src="http://page2.php?<?php echo strip_tags(SID);?>"> </script>
</body>
</html>

page2.php

<?
session_start();
echo $_SESSION["logged"];
?>

This should work according to php manual [php.net]
Best regards
Michal CIbor