15

I'm trying to create an image uploading website. In this, when a user logs in, I set a $_SESSION['id'] variable in php. Now, I wish to check if $_SESSION['id'] is set in my javascript file (general.js) in order to carry out certain functions. How should I go about doing it?

meagler
  • 287
  • 1
  • 2
  • 11

4 Answers4

28
<?php $session_value=(isset($_SESSION['id']))?$_SESSION['id']:''; ?>
    <html>
    <head>
    <script type="text/javascript">
    var myvar='<?php echo $session_value;?>';
    </script>
    <script type="text/javascript" src="general.js"></script>
    </head>
    <body>

    </body>
    </html>

In above code snippet I have initialized global variable myvar with value stored into php session variable into script file before general.js file is referenced in script.It will be accessible in general.js file

Rubin Porwal
  • 3,736
  • 1
  • 23
  • 26
  • I'm not able to access myvar in general.js – meagler Dec 30 '16 at 07:03
  • So the problem now is, if $_SESSION['id'] is set, then the code in general.js works fine...if it is not set, then my console shows the error "unterminated string literal" ..what's going wrong? – meagler Dec 30 '16 at 07:10
  • @eagleAtlantis Please find modified code snippet in above answer – Rubin Porwal Dec 30 '16 at 07:25
  • Those answers are terrible since you usualy put js in separate file. A legit solution woud be to set a and to get is with $('#id) or document.getElementbyId.value – Dice Aug 24 '18 at 22:09
  • @Dice What do you mean by "usually put js in separate file"? You still can, only that one line needs to be in ` – Radvylf Programs Mar 01 '19 at 23:22
  • This is super useful, thank you so much! – umbe1987 May 21 '19 at 10:48
  • how do you debug a php code embedded inside JS? This really looks odd to me. I am sure there is more elegant answer. Look at the syntax. Why no terminating semicolon. There is something very inconsistent with this answer. – Nguai al Jan 17 '20 at 01:27
  • @Nguaia, I think you are getting yourself confused with HTML tags and PHP tags. Give it a quick google. (y) – Ali Yousuf Jan 21 '20 at 11:16
8

A simple example please try this

<?php 
session_start();
$_SESSION['id'] = 12;

?>

<script>
alert(<?php echo $_SESSION['id']; ?>);
</script>

You can even use php variable and array as variable in js like below

<?php
    $id= $_SESSION['id'];
    $data= array('one', 'two', 'three');
?>
<script type="text/javascript">
    var idr = '<?php echo $id; ?>';
    var datar = <?php echo json_encode($data); ?>;
</script>
Passionate Coder
  • 7,154
  • 2
  • 19
  • 44
  • If I put in the beginning of my general.js, everything stops working..what should I do? – meagler Dec 30 '16 at 06:56
  • @meagler Why would you be putting that in a .js file to begin with? Both of these are .html – Radvylf Programs Mar 01 '19 at 23:23
  • Left something very important piece of information. The extension of this file must be .php not .html. If this file is kept with .html extension, this will not work. – Nguai al Jan 20 '20 at 16:54
  • I don't want to sound rude, but the occurrence of ` – Ali Yousuf Jan 21 '20 at 11:13
  • 1
    @AliYousuf - Sorry. You are right. I came across html extension and php extension code with this kind of hybrid code. So I just want to emphasize the importance of the extension. – Nguai al Jan 21 '20 at 17:49
5

Here PHP is server-Side execution and JavaScript is Client side execution. and $_SESSION is a server-side construct.So probably you can not access that directly using JavaScript You would need to store that variable in $_COOKIE to be able to access it client-side.

You can get that Session using PHP, and then use that for the JavaScript like this

<?php
$variablephp = $_SESSION['category'];
?>

<script>
var variablejs = "<?php echo $variablephp; ?>" ;
alert("category = " + variablejs);
</script>

Here you are getting Session like echo $variablephp using PHP, and the assign that value to JavaScript variable.

K.Suthagar
  • 2,226
  • 1
  • 16
  • 28
  • 1
    I think another option is saving the session inside text and read the text using document.getElementById("text_variable_name").value; – Rajib Jan 07 '18 at 10:58
  • you don't need double quotes around if the variable is a number. – Nguai al Jan 17 '20 at 01:30
  • @Nguaial, I have already answered that for you in answers below :) – Ali Yousuf Jan 21 '20 at 11:14
  • 1
    We can access _SESSION from javascript by writing the code as said. Saying that we can not access the _SESSION variable because php is server side and javascript is client side is very misleading. Yes, javascript is clientside but if the is included within the .php file, the code within the javascript script will be executed. – Gilbert Sep 20 '21 at 10:38
2

The best way is to echo the session ID in a javascript variable.

<script>
  var sessionId = "<?php echo $_SESSION['id']; ?>";

  // Your javascript code goes here
</script>
Ali Yousuf
  • 692
  • 8
  • 23
  • 1
    there is no need to put double quotes if the value is a numerical value. – Nguai al Jan 17 '20 at 01:29
  • You never apply calculation on `sessionId`.. It wouldn't matter if it's a numerical value or string. So quote caters both cases. – Ali Yousuf Jan 20 '20 at 07:59
  • I am getting this: JavaScript Error Handling: Unexpected Token: <. Running this is Chrome. – Nguai al Jan 20 '20 at 15:48
  • 1
    It is not supposed to be run in any browser directly. It's meant to be served by PHP server, which in turn fill up the `` segment. – Ali Yousuf Jan 21 '20 at 11:10