Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access PHP session variables from jQuery function in a .js file?

Tags:

How to access PHP session variables from jQuery function in a .js file? In this code, I want to get "value" from a session variable

$(function() {    $("#progressbar").progressbar({       value: 37    }); }); 
like image 700
Ahmad Farid Avatar asked Dec 06 '10 11:12

Ahmad Farid


People also ask

Can JavaScript access PHP session variable?

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.

Can I get session value in JavaScript?

JavaScript is a Client Side language and hence directly it is not possible to get Session value in JavaScript.

How can I access session variable in PHP?

Get PHP Session Variable Values From this page, we will access the session information we set on the first page ("demo_session1.php"). Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page ( session_start() ).


2 Answers

You can produce the javascript file via PHP. Nothing says a javascript file must have a .js extention. For example in your HTML:

<script src='javascript.php'></script> 

Then your script file:

<?php header("Content-type: application/javascript"); ?>  $(function() {     $( "#progressbar" ).progressbar({         value: <?php echo $_SESSION['value'] ?>     });      // ... more javascript ... 

If this particular method isn't an option, you could put an AJAX request in your javascript file, and have the data returned as JSON from the server side script.

like image 107
Erik Avatar answered Oct 22 '22 05:10

Erik


I was struggling with the same problem and stumbled upon this page. Another solution I came up with would be this :

In your html, echo the session variable (mine here is $_SESSION['origin']) to any element of your choosing : <p id="sessionOrigin"><?=$_SESSION['origin'];?></p>

In your js, using jQuery you can access it like so : $("#sessionOrigin").text();

EDIT: or even better, put it in a hidden input

<input type="hidden" name="theOrigin" value="<?=$_SESSION['origin'];?>"></input>

like image 23
Krimo Avatar answered Oct 22 '22 06:10

Krimo