Take the 2-minute tour ×

I have a PHP page that loads a session variable:

$user_id = $_SESSION['USER_ID'];


$(document).ready(function() {

        var user_id = <? echo $user_id; ?>
        var dataString = 'user_id=' + user_id;  
          type: "POST",  
          url: "../add_user.php",  
          data: dataString,  
        return false





share|improve this question
You can have the JavaScript file be processed by PHP. For example, name the file add_user.php, and then do <script src="add_user.php" type="text/javascript"></script>. –  Rocket Hazmat Dec 23 '11 at 16:12
I suppose you should use some global javascript variable inside your php-generated page or at least use a hidden field in which you can save your session_id value (and then access it from javascript) –  andreapier Dec 23 '11 at 16:14
Why not use the href attribute instead? add the full url to the link and just use that. –  Ignas Dec 23 '11 at 16:14

4 Answers 4

You can configure your webserver to treat .js files as PHP scripts, which would let you execute your PHP code from within the .js file.

However, if that's not acceptable, you can always do something like:

<script type="text/javascript">var user_id = <?php echo json_encode($user_id) ?>;</script>
<script type="text/javascript" src="add_user.js"></script>

to define the variable at your PHP script level, and then include the external .js as usual.

If $user_id is always numeric, then the json_encode() bit is overkill, but I've gotten into the habit of using that everywhere I'm generating JS code dynamically. Using json_encode guarantees you're inserting a syntactically correct JS snippet.

share|improve this answer
var user_id = <?php echo $user_id; ?>

Now you can use user_id in your add_user.js file. Also, I would advise against using PHP short tags.

share|improve this answer
A lack of a feature on some servers isn't a reason not to use it. Many hosters still run PHP 5.1, should we avoid using 5.3 features then? –  a sad dude Dec 23 '11 at 16:30
Short tags depend on a proper configuration setting, and if you're planning on deploying a project to different servers you should just get used to using the standard <?php tag since it's understood either way. "Seems like a small amount of work to assure interoperability" –  Aaron W. Dec 23 '11 at 16:36

You will still be able to reference your varible in your external js file

<script type="text/javascript">
var yourvar = <? echo $user_id; ?>;
share|improve this answer


After starting the session - read the value there.


share|improve this answer

Your Answer


