DCR DCR - 1 year ago 68
PHP Question

php javascript place script in a file

I tried the following:

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

it works fine. I'm trying to place the script in a file:

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

and then access it with:

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

but that's not working. Here's the error from the console:

crew.js:186 Uncaught TypeError: Cannot read property 'ldm' of null
at monthOnly (http://www.example.com/abc/public/js/crew.js:186:15)
at HTMLButtonElement.onclick http://www.example.com/abc/public/crew.php:3021:112)

I think the clue here is Cannot read property 'ldm' of null, it's not seeing the object. The file is being found when I check sources and network

Dez Dez
Answer Source

You need to send a Javascript header at the very beginning of the PHP file to inform the page that the PHP script is outputting a JavaScript file.

Header("content-type: application/x-javascript");

Also the final output of the PHP script needs to be a valid .js file, whatever the PHP outputs must conform to valid JavaScript syntax.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download