5

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.

5
  • 1
    style: is css , not javascript Commented Sep 9, 2013 at 5:49
  • Its part of a graphing script that uses it. Commented Sep 9, 2013 at 5:50
  • style is used for styling(css). Make your question clear Commented Sep 9, 2013 at 5:50
  • @Cherniv It may be a snippet from an Object literal. The : after style wouldn't really belong if CSS. Commented Sep 9, 2013 at 5:50
  • @JonathanLonowski you're 100% , i need to drink some coffee Commented Sep 9, 2013 at 5:52

4 Answers 4

2

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); ?>

Sign up to request clarification or add additional context in comments.

1 Comment

Why would you use a session that you didn't initiate?
1

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']; ?>

1 Comment

SO definitely needs a "post at the same time buddy" badge. For answers posted within 30 seconds.
0

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>

Comments

0

write

<?php
header('content-type: text/css');
?>

on begin from the css file with php extension

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.