Reputation: 561
I have a variable I need to drop into a javascript file and can't seem to get any results. I've tried making the .js into a php and adding an echo but it doesn't work.
I have a file that calls this in it
<script type="text/javascript" src="/file.php"></script>
Inside of file.php I have this line
style: {
color: '#<?php echo $_SESSION['colorOne']; ?>'
}
Everything works perfect when I replace the php with an actual color (#FFFFFF). I run into problems when I add the php.
Upvotes: 5
Views: 108
Reputation: 457
write
<?php
header('content-type: text/css');
?>
on begin from the css file with php extension
Upvotes: 0
Reputation: 32350
PHP can emulate any content you'd like, even Images, PDF and Office files.
First, don't confuse Javascript with CSS.
<link rel="stylesheet" href="/file.php">
At the beginning of the file.php
, make sure you start the session:
<?php
session_start();
?>
.style: {
color: #<?php echo $_SESSION['colorOne']; ?>;
}
If this does not work, you should debug if your session is init and working correctly, like make a new PHP file and put in <?php session_start(); print_r($_SESSION); ?>
Upvotes: 2
Reputation: 684
Your file needs to be processed by PHP when it gets requested. When you are on Apache you need to add
AddType application/x-httpd-php .MYFILEEXTENSION
to your .htaccess file. im not quite sure about nginx.
As a general idea, i've allways done this in the index.php file. Just print something into a global variable like
window.phpTransitionVariables = { ... };
with a script tag like this
<script type="text/javascript">
<? //print my php variables
</script>
Upvotes: 0
Reputation:
You need to call session_start() function before getting value of session, so, you need to put:
session_start();
At the top of that file.
Also, <script type="text/javascript" src="/file.php"></script>
is for JavaScript file, not external style sheet, and last note is you can print the value without single quotes:
color: #<?php echo $_SESSION['colorOne']; ?>
Upvotes: 1