8

I've a PHP session variable, $_SESSION['user'], alive throughout the session. In the head section, I've my JavaScript file included, scripts.js.

How do I pass the session variable into the JavaScript file if I want something like the following.

$.("#btn').click (
     function() {
        alert('<?php echo $_SESSION['user']; ?>');
     }
)

As the <?php ?> isn't recognized in the JavaScript file, the code above doesn't work. So I've to put in the PHP file itself, but how do I keep it in the JavaScript file?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ptamzz
  • 9,235
  • 31
  • 91
  • 147

5 Answers5

14

In your PHP file you could set your user as a global varibale:

<script type="text/javascript">
    var ptamzzNamespace = {
       sessionUser : '<?php echo $_SESSION['user']; ?>'
    }        
</script>

Include this before including your external JavaScript code.

Then in your JavaScript file you can use it:

$.("#btn').click (
     function() {
        alert(ptamzzNamespace.sessionUser);
     }
)

Additionally: If you're not sure if your session varibale can contain quotes itsself, you can use addslashes() to fix this problem:

<?php echo addslashes($_SESSION['user']); ?> even if this will maybe produce something you don't really want to display (because it produces a string with slashes) it will help that your code will not fail. (Thanks to Artefacto)

Would this be an option for you?

Chris
  • 7,675
  • 8
  • 51
  • 101
  • 3
    I wouldn't do that. Global JavaScript variables are nearly always a bad idea. – philonous Mar 15 '11 at 10:18
  • 1
    Why? The only thing that could happen is, that the global variable mixes up with some existing one out of some framework. To prevent you from this its easy to create your own namespace-object to store your global variables in. I edited the question to show how. – Chris Mar 15 '11 at 10:23
  • Ok, creating an own namespace-object definitely mitigates the risk of mixing something up. But in your answer you didn't use one ... ;) – philonous Mar 15 '11 at 10:30
  • -1 This won't work if `$_SESSION['user']` has single quotes or if it's an encoding that differs from that of the webpage. The best solution is to use `json_encode`. – Artefacto Nov 26 '11 at 17:42
  • @Artefacto `json_encode` only seems to work if `$_SESSION['user']` is encoded in UTF-8 otherwise the operation would fail. To fix the quoting problem `addslashes()` can be used. – Chris Apr 08 '13 at 15:21
3

Set the userID (in PHP) in an input type hidden in your file. In your JavaScript code you can read the hidden input types value.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sushil bharwani
  • 29,685
  • 30
  • 94
  • 128
1

You could set your server up to parse .js files as PHP. For example, in Apache config or .htaccess file:

<FilesMatch "scripts.js">
    AddHandler application/x-httpd-php5 .js
</FilesMatch>
0

Parse the included JavaScript file as PHP

Create a .htaccess file in you JavaScript directory and add the following line.

AddHandler php-cgi .js

<?php ?> tags till now be recognized by your JavaScript file.

Use Ajax to fetch the user ID

Create a file called getID.php which only echoes the users ID. Then in your JavaScript file you can use the following code.

$.get('getID.php', function(uid) {
  alert('User ID is:' + uid);
});

Create a script tag before including the JavaScript printing user ID.

<script type="text/javascript">
userID = <?php echo $_SESSION['user']; ?>;
</script>

You will now have access to the users ID using variable userID.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Andre Backlund
  • 6,843
  • 3
  • 20
  • 27
0

try with below logic

print ' <script type="text/javascript" language="javascript"> 
function checkForm() 
{ 
     var username = "'.$_SESSION['user'].'"; 
     if( username == '') 
     { 
        alert('No Times selected'); 
        return false; 
      }
}
</script>';
xkeshav
  • 53,360
  • 44
  • 177
  • 245