I have a Javascript file main.js and I need to use echo $_SESSION["username"] within it, but it doesn't work obviously. Is there any way I can do this / some kind of workaround?
2 Answers
You cannot execute PHP code in a .js file but there are ways to work around it. You could use an ajax call to get that variable (check out this link for ajax tips).
Depending on the information you wish to store, you could also get PHP to echo it into a specific element in your html page and then use JS to look up that element like this:
echo "<span id='usernameForJS' style='display: none;'>".$_SESSION['USERNAME']."</span>";
And then go and grab that elements inner html with JS like this:
var username = document.getElementById('usernameForJS').innerHTML;
I would advise AJAX just because then there is no need for almost redundant elements in your page. And obviously don't use the second method for anything sensitive.
4 Comments
main.js can then access that cookie value?main.js?go(); function go(){ alert();} because when you call go(); you haven't actually defined what go(); it is yet. If I had two files included in <script> tags, first.js and second.js and the first had the function declaration in and the second called the function, it would work as expected.There is a option I saw on css-tricks.com
https://css-tricks.com/snippets/htaccess/use-php-inside-javascript/
I have never tried on my own but commentators said it works.
There is also a explanation of how you could do this in the comments: https://css-tricks.com/snippets/htaccess/use-php-inside-javascript/#comment-85757
But don't forget taht this is a rather "hacky" way to do it, you should consider to open that javascript file and instantiate your class/function(or whatever is in this file) from the .php-page.
PHPwill not be executed on a.jsfile.