Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP variable in Javascript file

Tags:

javascript

php

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.

like image 404
Milksnake12 Avatar asked Oct 22 '22 01:10

Milksnake12


1 Answers

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

like image 85
Daniel W. Avatar answered Oct 27 '22 11:10

Daniel W.