Recent Posts
- (10/14) Forcing A Single Join in CakePHP PaginationTAGS:CakephpCakephp 13DatabaseErrorsHabtmMysqlMssqlWeb ProgrammingUsage
- (08/11) Inserting NOW() into MySQL Using CakePHPTAGS:CakephpDatabaseMysqlMssqlWeb ProgrammingUsage
- (08/07) Best PaginateCount for CakePHP - with Group By SupportTAGS:CakephpBehaviorsWeb ProgrammingUsageDatabaseExampleMysqlHabtmHack
- (04/03) CakePHP Error Messages Not Showing on FormTAGS:CakephpCakephp 13Web ProgrammingErrorsUsage
- (02/06) Sorting Paginated Results Using a Related Model Field in CakePHPTAGS:CakephpWeb ProgrammingUsageExample
- (11/02) Changing CakePHP's Model useTable on the FlyTAGS:CakephpWeb ProgrammingMysqlDatabaseExampleTutorial
- (10/18) The Funniest Error Message Ever - Thank You EclipseTAGS:EclipseWeb ProgrammingErrorsHumorWindowsUsageSoftwarePhpCakephp
- (09/27) Upgrading CakePHP Application to 1.3 (from 1.2)TAGS:CakephpUpgrade
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 3,761 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.

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