AlexB
AlexB

Reputation: 13

"Unexpected token <" when using <?php in a Javascript file

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

Answers (3)

furtive
furtive

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

David
David

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):

  1. Defining that one var on a PHP page which references the JS file, thereby making it available to the JavaScript code.
  2. Putting the value in a page element somewhere that it can be accessed by JavaScript code, either as a form value or perhaps a data value.
  3. Making an AJAX request to the server to get that value (and other values) after the page has been loaded.

Upvotes: 2

MajicBob
MajicBob

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

Related Questions