Search code examples
javascriptphphtmljsonsession-variables

How do I access session variable from php in external javascript


I know this has been asked before but there's no explanation from start to finish. I have a login.php from which I want to get $_SESSION['user_id']

from

<?php
include "connect.php";

session_start();

$email=$_POST['email'];
$password=$_POST['password'];

$select_data=mysql_query("select * from user where email='$email' and password='$password'");

if(isset($_POST['email']))
{
if($row=mysql_fetch_array($select_data))
 {
  $_SESSION['user_id']=$row['id']; //The variable want to access from ext.js

  echo "success";
 }
 else
 {
  echo "fail";
 }
 exit();
}
?>

By the way, this authenication works fine

My Main.php


<!DOCTYPE html>
<?php include 'connect.php';
session_start();
echo $_SESSION['user_id']; //works fine
//;
?>
<body>
//contents
<script src="login.js"></script>
<script src="postad.js"></script> //the script from which I want to get $SESSION_['user_id']

</body>

I want this variable to insert later on in a database. Any suggestions?


Solution

  • If you want to call php variable in external js file then you have to store value in input.

    Main.php

    <body>
    <input type="hidden" value="$SESSION_['user_id']" class="user_id">
    <script src="login.js"></script>
    <script src="postad.js"></script> //the script from which I want to get $SESSION_['user_id']
    
    </body>
    

    postad.js

    $(function(){
        var user_id = $('.user_id').val();
        alert(user_id);
    });
    

    And if you want to use in same file then you can directly use php echo.

    Main.php

    <body>
        //content..
    
    <script>
        var user_id = "<?php echo $SESSION_['user_id'] ?>";
    </script>
    <script src="login.js"></script>
    <script src="postad.js"></script> // console.log(user_id); that file you'll get that id.
    </body>