PHP Session variable in external JS file is null - javascript

I am trying to get a PHP session variable into an external JS file. In the JS file, I want to read and use the value of the session variable, but also assign a new value to the Session variable.
I tried this :
php file:
<?php session_start();?>
<html>
<head>
<title></title>
<script src="testjs.php" type="text/javascript"></script>
</head>
<body>
<?php $_SESSION['Count'] = 1; ?>
</body>
</html>
javascript file:
<?php header("Content-type: application/javascript"); ?>
alert("I am an alert box!");
var test = <?php echo $_SESSION['Count'] ?>;
alert(test);
<?php $_SESSION['Count'] = 2 ?>
test = <?php echo $_SESSION['Count'] ?>;
alert(test);
But I keep getting an empty value and my chrome inspector keeps giving me this error: Uncaught SyntaxError: Unexpected token ; for this line: var test = ;
Help needed :)

You need to start the session in the js(php) file:
<?php
session_start();
header("Content-type: application/javascript"); ?>
alert("I am an alert box!");
var test = <?php echo $_SESSION['Count'] ?>;
alert(test);
<?php $_SESSION['Count'] = 2 ?>
test = <?php echo $_SESSION['Count'] ?>;
alert(test);
This is because the browser makes a separate request to this file, as script tag is not the same as a php include.
NOTE interspersing php and js like this is not a good idea. Although the code above will work, it will blur the mental line between serverside (php) and client side, which can lead to broken code like the following:
var abool = false;
var test = <?php echo $_SESSION['Count'] ?>;
if(abool){
<?php $_SESSION['Count'] = 2 ?>
}
var test = <?php echo $_SESSION['Count'] ?>;
alert(test);
In the above, test will = 2, because the php code is executed before the javascript, so the js if block has zero impact on the php, which is essentially:
<?php
echo $_SESSION['Count'];
$_SESSION['Count'] = 2;
echo $_SESSION['Count'];

Looking at your php file, you have a rogue ; at the end of this line:
<?php $_SESSION['Count'] = 2 ?>;
The output would just be:
;
Move the semicolon and you're fine:
<?php $_SESSION['Count'] = 2; ?>
EDIT: It looks like you're not opening the session in your JS file... You're not using require() or include() so I imagine you should start with session_start() before sending headers.

You need to call session_start(); before you access $_SESSION variables. Reference to "php" file in <script> tag makes another separate request to the server.
http://php.net/manual/en/function.session-start.php

you can't call php code in js file ...
php will work when the file extension is php...
for this you need to do :
create/assign javascript variable/object in php file and access it in js file

Related

How can I pass the PHP variable to JavaScript?

I am new to PHP. I want to pass the php variable into my javascript file. But it was not converted. I already defined the value of $val in php file. I write following code in my index.js file;
var val = "<?php echo $val ?>";
console.log(val);
but my console shows output as : <?php echo $val ?>. It is not taking the php variable value. Any help?
you have to include script at bottom of your page PHP FILE
<script>
var val = "<?php echo $val ?>";
console.log(val);
</script>

How to access php SESSION variable in javascript [duplicate]

This question already has answers here:
Pass a return value from php to js
(1 answer)
How to access php session in javascript file?
(4 answers)
Closed 6 years ago.
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?
<?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
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>
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.
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>

SyntaxError: missing ; before statement - no obvious error?

I keep getting the above error referring to the second line of my code below and have no idea why! With the below part removed my project works ok with no problems but I keep gettig that error with it in, hence it wont run.
<?php
$myVar = $_POST['dropdown'];
?>
<script type="text/javascript">
var myVar = <?php echo '$myVar';?>
console.log(myVar);
</script>
This is probably your issue
var myVar = <?php echo '$myVar';?>
This should work, assuming you did want the single quotes around the PHP variable, and this also contains the javascript end-of-statement ; :
var myVar = <?php echo "'$myVar';";?>
If you did not want the single quotes then this should do :
var myVar = <?php echo $myVar . ';';?>

insert php value inside javascript function

I have this command inside my javascript to create a cookie with a specific value.
...
document.cookie="superpage=John Doe;secure=true";
...
My goal: I want the content of this cookie inserted via PHP.
So I tried this: In a separate PHP file i declared
$myvalue = "superpage=John Doe;secure=true";
Then I changed the javascript cookie creation to this:
...
document.cookie= '<?php echo $myvalue; ?>';
...
Cookie is then created but with the value <?php echo $myvalue and not the string I defined via PHP. Any help is highly appreciated.
Put your JavaScript on a page with .php extension and your code will work, .i.e:
file.php
<?php
$myvalue = "superpage=John Doe;secure=true";
?>
then, on the same page, outside the php block:
<script>
document.cookie= '<?php echo $myvalue; ?>';
</script>
There seems to be confusion on how to mix php with javascript. The only way to do so would be with javascript inside a php file:
<?php
php code.....
$myvalue = "superpage=John Doe;secure=true";
echo '
<script>
javascript code....
document.cookie= '.$myvalue.'
</script>';
?>

php echo of javascript with php echo inside

I am very new to PHP and JavaScript. I am currently using echo in PHP to run some JavaScript on the page. I need to make a new javascript array and a new variable that are equal to an existing PHP array and variable, so I did this:
var messages = <?php print_r($messages)?>
var list = <?php echo $message['user_name'].': '.$message['text'].' ('.date('d/m/Y H:i:s', $message['date']).')'.'<hr />'; ?>
However, there is a problem caused by my using echo to echo script containing echo. How would I solve this. I would like to echo it because it is only about 4 lines long, so is there an alternative.
Thank you in advance.
Edit: This is the whole JavaScript. It is for a messaging system. $messages is declared from another PHP function, and the basic aim of this code is to 'refresh' the echo every few seconds so that the user can see new messages without having to refresh their page:
echo '<script type="text/javascript">;';
echo 'var messages = <?php print_r($messages)?';
echo 'var list = <?php echo $message['user_name'].': '.$message['text'].' ('.date('d/m/Y H:i:s', $message['date']).')'.'<hr />'; ?>';
echo 'setInterval(function(){console.log("hello")},3000);';
echo '</script>';
Not getting what you want,but if you want to use php array in javascript than make it javascript array
<script>
<?php $test_arr = array('apple','banana','mango');?>
var js_array = <?php echo json_encode($test_arr);?>;
</script>
output
<script>
var js_array = ["apple","banana","mango"];
</script>
Your Javascript will execute on the client, not on the server. This means that foo is not evaluated on the server side and therefore its value can't be written to a file on the server.
The best way to think about this process is as if you're generating a text file dynamically. The text you're generating only becomes executable code once the browser interprets it. Only what you place between <?php tags is evaluated on the server.
By the way, making a habit of embedding random pieces of PHP logic in HTML or Javascript can lead to seriously convoluted code. I speak from painful experience.

Categories