Recent Posts
- (09/10) Fixing Warning: the ECDSA host key for 'github.com' differs from the key for the IP addressTAGS:Web Server Admin
- (12/26) CakePHP 3 - Getting List of Column Definitions from a Table (like schema())TAGS:CakephpCake3
- (09/14) Change Order of Loaded Behaviors in CakePHP 3TAGS:Cake3CakephpWeb ProgrammingPhp
- (05/29) CakePHP 3 - Accept JSON Header Only Working When Debug FalseTAGS:Web ProgrammingCakephpCake3
- (05/23) Remove All Events from Google Calendar (Reset Calendar)TAGS:Web ProgrammingPhp
- (11/08) Google Tag Manager (GTM) Not Firing Default PageView EventTAGS:Web ProgrammingJavascriptGoogle Tag Manager
- (10/13) In PHP, how do you get __toString() Magic Method Result without calling echo?TAGS:CakephpCake3Cakephp 13PhpWeb Programming
- (11/14) Getting output from shell_exec() at all timesTAGS:Web ProgrammingWeb Server Admin
Subscribe to my feed
MainelyDesign.com Blog
Best Approach to Dynamic Javascript in CakePHP Views
Posted on 05/29/2010 at 12:36 pm by Kevin Wentworth
Viewed 23,307 times | 5 comments
I always knew in the back of my mind that there was a better way of creating dynamic javascript than the method I was using. CakePHP has a great function as part of the $View controller: $View->addScript($jscript, false) will add a script block to your template header. This is the command I use to send javascript created in a Cake view up to the header, which is where most javascript should live. The best approach to adding dynamic javascript to your CakePHP views is to implement PHP's output buffering, combined with $View->addScript().
Buffer That Javascript and then use CakePHP's $this->addScript()
Here's the code I use to allow me to write "native" javascript, i.e. not having to worry about escaping quotes one way or the other (see below).
- <?php
- ?>
- <script type="text/javascript" language="JavaScript">
- function checkFormValidation(whichForm) {
- var why = "<?php echo $data['Model']['text']; ?>";
- var errorsFound = 0;
- ...
- document.waiver_and_consent.elements['SubmitButton'].disabled = true;
- document.waiver_and_consent.elements['SubmitButton'].value = " Please wait... ";
- return true;
- }
- </script>
- <?php
- ob_end_clean(); //must clean buffer or javascript above will print TWICE (one inline, one in header)
- echo $this->addScript($jscript, false); //add script to header
- ?>
The Old Way... using a PHP string. Yuck!
I use to have huge javascript "strings" that would need to be properly quoted and escaped where necessary. What a pain! I can't believe I ever did it this way:
- <?php
- $jscript = '<script type="text/javascript">
- function checkFormValidation(whichForm) {
- var why = "'. $data['Model']['text'] .'";
- var errorsFound = 0;
- document.waiver_and_consent.elements[\'SubmitButton\'].disabled = true;
- document.waiver_and_consent.elements[\'SubmitButton\'].value = " Please wait... ";
- return true;
- }
- ';
- echo $this->addScript($jscript, false); //add script to header
- ?>
Hope this saves someone from having to debug poorly escaped javascript in a PHP string on top of poorly written javascript.
Cheers,
-Kevin Wentworth
Tags for Best Approach to Dynamic Javascript in CakePHP Views
Cakephp | Web Programming | Jquery | Usage | Example | Php
Comments for this Posting
Posted by Schiho
on 5/11/10
I would like to ask a question.
In your approach you have everything in one file. I would like to linked js file, so that my view does not get confusing. But how do i pass my linked "php" file the data variable?
would be nice to know
thanks
Posted by miCRoSCoPiC^eaRthLinG
on 21/12/10
@shreyas: That's what I had tried using first - but heredoc does a miserable job as it tries to parse anything that begins with a $ and if you are using any of the regular JS frameworks where the functions are encased in a global $() namespace - you are royally screwed, my friend :D
But fear not, as in situations like these it's NOWDOC syntax that saved the day.
Anyway, the one presented in this article is a much better solution.
Cheers,
m^e
Posted by Fang
on 14/10/11
actually, i found out the following is exactly what this is ,
http://book.cakephp.org/view/1606/scriptEnd
$this->Html->scriptStart(array('inline' => false));
echo $this->Js->alert('I am in the javascript');
$this->Html->scriptEnd();
it's not detailed documented, however, you can put any javascript (including comments, any html) between start and end, don't forget there's no echo for those two lines.
Sorry, comments are closed for this posting.
Please Email Kevin if you have any questions. Thanks!
Posted by Schiho
on 5/11/10
I was just waiting for that. There are a lot of old cakephp helpers written like your "yuck" code :). It was so annoying to find a bug!
thanks for the clarification.
http://www.schiho.com