Reputation: 13
Being new to this, I'm trying to pass a variable from PHP to Javascript.
In my php page, I use a test variable:
$testval = "x";
In my .js file:
var exarr = <?php echo json_encode($testval); ?>;
I've tried several things, but it seems I always get Unexpected token < when I include "
What am I doing wrong ?
Thanks !
Upvotes: 0
Views: 9463
Reputation: 1699
.js files are not compiled by PHP. The easiest workaround is to put the Javascript in a <script>
block within a .php, but you're making one of the most basic of serverside/clientside mistakes and should rethink your entire approach.
Upvotes: 1
Reputation: 219047
In order to use PHP code in any file, the web server has to run that file through the PHP processor. This is configured to happen by default with .php
files, but not with .js
files.
You could configure your server to process .js
files as PHP, but that's generally unwise. At the very least, it creates a lot of unnecessary overhead for those files since most of them won't (or shouldn't) have PHP code.
Without knowing more about the structure of what you're trying to accomplish, it's difficult to advise a "best" approach. Options include (but may not be limited to):
var
on a PHP page which references the JS file, thereby making it available to the JavaScript code.Upvotes: 2
Reputation: 497
If you have that in a js file (like somefile.js) then PHP isn't going to parse that file by default. In the PHP file that links to that JS you can output a script tag and the var you want like:
echo "<script>var exarr = " . json_encode($testval) . "; </script>";
And make sure your script is linked in after that code;
Upvotes: 1