0

I have a php array:

$x = array("1","2","3");

I also have javascript code to convert the php array into a javascript array:

var x = <?php echo json_encode($x) ?>;

It works perfectly when I type this out in the index.php file (ie - I can use that array in any other javascript file):

<script type="text/javascript"> var x = <?php echo json_encode($x) ?>; </script>

But it doesn't work when I do this:

<script type="text/javascript" src="file.js"></script>

And file.js contains:

var x = <?php echo json_encode($x) ?>;

I just can't understand why this is the case, any idea why? Thanks in advance.

1
  • .js files cannot process PHP Commented Nov 25, 2013 at 8:49

2 Answers 2

3

External JS files are not PHP files. They will NOT be parsed by PHP parser (web server).

To "enable" PHP tags in external JS files, you can name it with script.js.php (ends with .php), and the example contents are as follow:

<?php
header('Content-Type: text/javascript');
?>
var x = <?php echo json_encode($x) ?>;

and import it with:

<script type="text/javascript" src="script.js.php"></script>

Apart from using the above method, here is another way to "merge" JS and PHP, in a tricky way:

Contents in an external PHP file (assume the file name is method2.inc.php):

<script type="text/javascript">
var x = <?php echo json_encode($x) ?>;
</script>

Instead of using <script> tag to include it into original PHP file, you use:

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Method 2</title>
<?php require_once('method2.inc.php'); ?>
</head>
<body>
<-- body goes here -->
</body>
</html>

Note: The filename is free to change, as long as its file extension is .php.

12
  • Is necessary to call .js ? Or just for info ? Commented Nov 25, 2013 at 8:56
  • @Don what do you mean? Commented Nov 25, 2013 at 9:25
  • I just tried it but the javascript code isn't getting parsed, it simply returns text. Commented Nov 25, 2013 at 9:25
  • How & where did you load the file? Commented Nov 25, 2013 at 9:27
  • @ShivanRaptor I mean that if I name the file script.php, will work or not ? Commented Nov 25, 2013 at 9:28
0

I just can't understand why this is the case, any idea why?

Because your server does not send files with ending .js through the PHP parser by default …

You can f.e. name the file .php instead, then it will be parsed. But be aware that you’ll have to send the appropriate Content-Type header yourself in that case:

header('Content-Type: …');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.