PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, February 3, 2022

[FIXED] Cakephp: how to pass values into a javascript file?

 February 03, 2022     cakephp, javascript, php     No comments   

Issue

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.


Solution

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.



Answered By - Luke Dennis
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing