How to pass PHP session variable into Javascript/jQuery function?

By : Michael
Source: Stackoverflow.com
Question!

I have a PHP page that loads a session variable:

$user_id = $_SESSION['USER_ID'];

Previously, I included my Javascript/jQuery within that page, and added <? echo $user_id; ?> to set the Javascript variable:

$(document).ready(function() {

     $(".button").click(function() {
        var user_id = <? echo $user_id; ?>
        var dataString = 'user_id=' + user_id;  
        $.ajax({  
          type: "POST",  
          url: "../add_user.php",  
          data: dataString,  
        });  
        return false
     });


});

However, I'd like to move my Javascript to a separate page and call the script from my PHP page:

<script src="add_user.js" type="text/javascript"></script>

If I do this, I can no longer user <? echo $user_id; ?>, so what is the best way to pass my PHP variable into the Javascript/jQuery function?

By : Michael


Answers

Just start the session on the other side. Its is also more secured, considering that JS data may be corrupted, even deliberately and may be exploited (security).

After starting the session - read the value there.

Of course, this is valid for scripts on the same vhost.

By : Rolice


This video can help you solving your question :)
By: admin