21

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
   });
});
Amaan Iqbal
  • 761
  • 2
  • 9
  • 25
Ahmad Farid
  • 14,398
  • 45
  • 96
  • 136

7 Answers7

52

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.

Erik
  • 20,526
  • 8
  • 45
  • 76
  • What if I want to put it in the $(document).ready() function which is in the .js file? – Ahmad Farid Dec 06 '10 at 11:14
  • 1
    the `.js` extension doesn't mean anything: rename it .php and use your session variables as I've shown above. Your javascript files could be `file.gibbldygook` and they would still work. – Erik Dec 06 '10 at 11:16
  • You mean I can write PHP code in the .js file? What should be the structure now? How can I put two functions under the $(document).ready() at two different files? – Ahmad Farid Dec 06 '10 at 11:19
  • 2
    You're a bit unclear, Ahmad. The browser does not care what your javascript file is named. Rename your file from "script.js" to "script.php" then use your session variables as I've shown above. And you can use as many `$(document).ready()` blocks in as many files as you like, it will work fine. – Erik Dec 06 '10 at 11:28
  • yup...I've done that in past too, clearly I need more coffee this morning! – SW4 Dec 06 '10 at 11:34
  • 2
    You should also set the file type to JavaScript with a simple PHP header, put this at the top of your JS (.php) file: `` It works without it, but it is good to set it to that just so the browser knows its contents is JavaScript. – Nathan Dec 30 '11 at 05:04
  • Is there any performance(faster/slower) issue using `avascript.php` instead of `javascript.js`??? – MD SHAHIDUL ISLAM Jun 19 '14 at 10:08
  • Is this still supposed to work? Using the posted code, I'm seeing: SyntaxError: expected expression, got '<' – orfdorf Jul 14 '15 at 04:41
  • This solution does not work if you are using a modern JavaScript compiling build process. However, you can get your data with AJAX instead. – ssc-hrep3 Feb 10 '16 at 14:03
  • @me the stored session values are empty after page reload, or after a second JQuery $.post call. – Jan Bludau Jun 08 '17 at 14:50
10

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>

Krimo
  • 954
  • 8
  • 20
  • 1
    That's better solution than making AJAX call that takes process time. Unless the session variable is a sensitive information like password etc. – trante Jul 05 '12 at 07:42
7

If you want to maintain a clearer separation of PHP and JS (it makes syntax highlighting and checking in IDEs easier) then you can create JQuery plugins for your code and then pass the $_SESSION['param'] as a variable.

So in page.php:

<script src="my_progress_bar.js"></script>
<script>
$(function () {
    var percent = <?php echo $_SESSION['percent']; ?>;
    $.my_progress_bar(percent);
});
</script>

Then in my_progress_bar.js:

(function ($) {
    $.my_progress_bar = function(percent) {
        $("#progressbar").progressbar({
            value: percent
        });
    };
})(jQuery);
icc97
  • 11,395
  • 8
  • 76
  • 90
2

You can pass you session variables from your php script to JQUERY using JSON such as

JS:

jQuery("#rowed2").jqGrid({
    url:'yourphp.php?q=3', 
    datatype: "json", 
    colNames:['Actions'], 
    colModel:[{
                name:'Actions',
                index:'Actions', 
                width:155,
                sortable:false
              }], 
    rowNum:30, 
    rowList:[50,100,150,200,300,400,500,600], 
    pager: '#prowed2', 
    sortname: 'id',
    height: 660,        
    viewrecords: true, 
    sortorder: 'desc',
    gridview:true,
    editurl: 'yourphp.php', 
    caption: 'Caption', 
    gridComplete: function() { 
        var ids = jQuery("#rowed2").jqGrid('getDataIDs'); 
        for (var i = 0; i < ids.length; i++) { 
            var cl = ids[i]; 
            be = "<input style='height:22px;width:50px;' `enter code here` type='button' value='Edit' onclick=\"jQuery('#rowed2').editRow('"+cl+"');\" />"; 
            se = "<input style='height:22px;width:50px;' type='button' value='Save' onclick=\"jQuery('#rowed2').saveRow('"+cl+"');\" />"; 
            ce = "<input style='height:22px;width:50px;' type='button' value='Cancel' onclick=\"jQuery('#rowed2').restoreRow('"+cl+"');\" />"; 
            jQuery("#rowed2").jqGrid('setRowData', ids[i], {Actions:be+se+ce}); 
        } 
    }
}); 

PHP

// start your session
session_start();

// get session from database or create you own
$session_username = $_SESSION['John'];
$session_email = $_SESSION['johndoe@jd.com'];

$response = new stdClass();
$response->session_username = $session_username;
$response->session_email = $session_email;

$i = 0;
while ($row = mysqli_fetch_array($result)) { 
    $response->rows[$i]['id'] = $row['ID']; 
    $response->rows[$i]['cell'] = array("", $row['rowvariable1'], $row['rowvariable2']); 
    $i++; 
} 

echo json_encode($response);
// this response (which contains your Session variables) is sent back to your JQUERY 
genesis
  • 50,477
  • 20
  • 96
  • 125
Mark
  • 21
  • 1
1

You cant access PHP session variables/values in JS, one is server side (PHP), the other client side (JS).

What you can do is pass or return the SESSION value to your JS, by say, an AJAX call. In your JS, make a call to a PHP script which simply outputs for return to your JS the SESSION variable's value, then use your JS to handle this returned information.

Alternatively store the value in a COOKIE, which can be accessed by either framework..though this may not be the best approach in your situation.

OR you can generate some JS in your PHP which returns/sets the variable, i.e.:

<? php
echo "<script type='text/javascript'>
    alert('".json_encode($_SESSION['msg'])."');
</script>";
?>
SW4
  • 69,876
  • 20
  • 132
  • 137
0

This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.

Three javascript libraries are required, createCookie, readCookie and eraseCookie. These libraries are not mine but I began using them about 5 years ago and don't know their origin.

createCookie = function(name, value, days) {
if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
}
else var expires = "";

document.cookie = name + "=" + value + expires + "; path=/";
}

readCookie = function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
eraseCookie = function (name) {
   createCookie(name, "", -1);
}

To call them you need to create a small PHP function, normally as part of your support library, as follows:

<?php
 function createjavaScriptCookie($sessionVarible) {
 $s =  "<script>";
 $s = $s.'createCookie('. '"'. $sessionVarible                 
 .'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
 $s = $s."</script>";
 echo $s;
}
?>

So to use all you now have to include within your index.php file is

$_SESSION["video_dir"] = "/video_dir/";
createjavaScriptCookie("video_dir");

Now in your javascript library.js you can recover the cookie with the following code:

var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';

I hope this helps.

0

Strangely importing directly from $_SESSION not working but have to do this to make it work :

<?php
$phpVar = $_SESSION['var'];
?>

<script>
    var variableValue= '<?php echo $phpVar; ?>';
    var imported = document.createElement('script');
    imported.src = './your/path/to.js';
    document.head.appendChild(imported);
</script>

and in to.js

$(document).ready(function(){
alert(variableValue);
// rest of js file
Ardhi
  • 2,855
  • 1
  • 22
  • 31