3

I tried the following:

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

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

6
  • Do you get an error in the developer console? ("That's not working" is a bit too vague to know exactly what's going on...) Commented Nov 7, 2016 at 0:17
  • 1
    Why don't you just jQuery.getJSON() the file? Commented Nov 7, 2016 at 0:27
  • I'm trying to pass a php array $cdata to javascript Commented Nov 7, 2016 at 0:29
  • Question: can I do this with a control file? I have a abc.php file that I use to render forms. Can I start the file with the <?php HEADER....; Do all my server side stuff. end php with ?> and then echo out the data I want to pass to javascript with var jsdata = <?php echo json_encode($phpdata); ?>; ?? Commented Nov 7, 2016 at 1:08
  • @DCR do you read or just blatantly ignore suggestions? You're over complicating what you're trying to do. Just run a $.getJSON(...) call to a PHP file that's spitting out valid json. Commented Nov 7, 2016 at 1:24

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I tried this as my file: <?php Header("content-type: application/x-javascript"); var cdata = echo json_encode($cdata); ?>; and got a 500(internal server error)
@DCR because that isn't valid PHP. What you want is something like [this] (eval.in/673017)
still don't understand the $.getJSON(). I don't have a json file to load just a complicated array of arrays in $cdata. Anyway, the rest of this was helpful. Thanks.

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.