I have a variable set in one file, varset.php, which I echo on all the pages of my site. If I ever need to change this variable, I update it in varset.php and it updates the variable throughout my whole site. The problem is that I have a .js file and I need to echo this variable in it. In all my php pages, I of course have: include("varset.php"); echo $variable; PHP: I just can't figure out how I can get this variable to echo from a .js file. If anyone could help me out, Id greatly appreciate it & +rep! Thanks
<script type="text/javascript" language="javascript"> <!-- <?php $someVar = 2; echo "someVar = ". $someVar; ?> // --> </script> Code (markup): That should work.
Thanks, But the variable is set in an external php file instead of in the actual js page. In your example, echo "someVar = ". $someVar; How would I call that variable from an external php file?
You can do that in this way: varset.php content: <?php $variable = 1; ?> PHP: Then the .js file content: <script type="text/javascript" language="javascript"> <!-- <?php include("varset.php"); echo $variable; ?> // --> </script> Code (markup): In this way you can change the $variable value and you can display that variable in the .js file.
^ Yeah, all you needed to do was include the file where the variable was set. Mine was just a basic example
Its not working because my .js file is not processed as a php file. I have devpedia working on it for me now, but we still havn't quite figured it out.
Why don't you just declare the javascript variables at the top of the actual .php page, then they can be used later on when your js document is included
Because my js is not included in a php file- its a completely seperate js file that does not work with any php whatsoever.
You can make a PHP file be JavaScript by setting a header like this: <?php header('Content-type: text/javascript'); ?> //a bunch of regular JavaScript code goes here, and you are allowed to insert PHP also, wrapped in PHP tags PHP: Then, link to it just like you would a regular script: <title>Example</title> <script type="text/javascript" src="js/example.php"></script> </head> HTML: Note the the file linked to is .php Just be aware that this external (now JavaScript) file, will not share the same global namespace for PHP, though it will for JavaScript, so you will need to pass variables to it in some way, means it needs either cookies, its own database connection, or whatever you can think of. The PHP data will be encapsulated, but the JavaScript will be just like a normal script. I've built applications this way, when I don't want my AJAX page, which also has PHP on it, interfering with the global namespace of the front-end. It can be very powerful to have a hybrid server-side/client-side script like this, in an external file.