Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

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?

share|improve this question
add comment

marked as duplicate by Benjamin Gruenbaum yesterday

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

5 Answers

up vote 12 down vote accepted

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?

share|improve this answer
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 8 '13 at 15:21
add comment

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.

share|improve this answer
    
Not a bad idea as well! –  Chris Mar 15 '11 at 10:33
add comment

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>
share|improve this answer
add comment

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>';
share|improve this answer
add comment

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.

share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.