Skip to content
Advertisement

Cakephp: how to pass values into a javascript file?

I have some javascript that is being included in a view and I used inkedmn’s method in this thread: adding-page-specific-javascript-to-each-view-in-cakephp

So I now have the following code in my view:

$this->set('jsIncludes',array('google'));   // this will link to /js/google.js

But I need to pass some values from the view into the javascript file and I’m unsure of how to accomplish this.

Update: I guess one option would be to echo the values in the php file, enclose in a div tag, and then use a getElementById() in the javascript code.

Advertisement

Answer

You should be able to inject a <script> tag directly into the HTML with the data you want:

<script type="text/javascript">
var mynum = <?php echo intval($num); ?>;
var mystring = "<?php echo addslashes($string); ?>";
var myarray = <?php echo json_encode(array("one" => 1, "two" => 2)); ?>;
</script>

Any javascript elsewhere should be able to use these variables.

Note: if the code using this data runs earlier in the page, they obviously won’t see these variables yet. If that’s the case, either ensure that your data is loaded first, or you can delay the code from running until the page is fully loaded, using either setTimeout() or a document.onready event.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement