Reputation: 317
I have 2 files. A PHP file that sets a session variable and a Jquery(.js) file that needs to access that session variable. But Javascript is client sided and PHP is server sided so how would I be able to create a javascript variable that has the value of that PHP session variable(assuming it's a string).
The following doesn't work(because it has to be in the same page I think):
var php_var = "<?php echo $php_var; ?>";
Thanks!
Upvotes: 0
Views: 2534
Reputation: 34406
Given a PHP file (foo.php) which contains the following:
<?php
session_start();
$_SESSION['foo'] = 'foo';
echo $_SESSION['foo'];
?>
You could use jQuery to get the value:
$.get('foo.php', function(data) {
var foo = data; // 'foo' in this case
});
I am using the $.get
AJAX shortcut method but you could also go with any of the other jQuery AJAX methods.
Upvotes: 2