user3030521
user3030521

Reputation: 5

Why must json_encode appear in php file and not in an external javascript file?

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.

Upvotes: 0

Views: 374

Answers (2)

Raptor
Raptor

Reputation: 54222

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.

Upvotes: 3

C3roe
C3roe

Reputation: 96339

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: …');

Upvotes: 0

Related Questions