0

I am currently working on a project where i wanna implement jQuery to cakephp 2.0.

I have followed the guide at: http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html

i.e. I have downloaded jquery-1.8.1.js (also tried the .min.js file) and put it in app/webroot/js. In the default layout file i have added

echo $this->Html->script('jquery');

and just before the end of the body tag i have added

echo $this->Js->writeBuffer();

In my controller i have added

public $helpers = array('Js' => array('Jquery'));

When i reload my page and check the source code I see that the link to the jQuery file works correctly. But when I try to add a simple script (just adding an alert) like this (in the view file):

$alert = $this->Js->alert('Hey there');

nothing happens...

Any kind person out there that might have any suggestion to what I do wrong? I have spent hours looking looking at the internet and following different guides but still can get a simple thing as an alert working.

7
  • 1
    do you also echo the $alert then? my guess: you are not even printing this line. also, why not using firebug to properly debug js? then it would tell you exactly what the problem is - if its js related. Commented Sep 30, 2012 at 10:48
  • if i echo the $alert it just prints alert("Hey there"); but I dont get a pop-up... Commented Sep 30, 2012 at 10:59
  • better than not printing it, isnt it? is it encapsulated in a <script> tag? you cant just throw around with js outside of the js scope. Commented Sep 30, 2012 at 11:07
  • First of all i appreciate your help! if i write: <script> <? $alert = $this->Js->alert('Hey there'); echo $alert; ?> </script> i do get the pop-up window but i thought the point of having the Js helper was so i wouldnt need to write all that, or am i wrong? Commented Sep 30, 2012 at 11:15
  • 8
    Forget the Js helper and directly write jquery code. You will find it in adequate anyways when you want to do slightly more complex things. Commented Sep 30, 2012 at 13:01

2 Answers 2

3

According to CakePHP 2.0 documentation: "by default, alert does not buffer, and returns the script snippet."

So by default:

echo $this->Js->alert('Hey there'); // outputs alert("Hey there");

To override this behaviour and add the script to the buffer:

echo $this->Js->alert('Hey there', true);

To write the buffer (commonly right before </body>):

echo $this->Js->writeBuffer();
Sign up to request clarification or add additional context in comments.

Comments

0

As an alternative you can use scriptBlock:

$jscript = "alert('Hey there!');";
echo $this->Html->scriptBlock($jscript, array('inline'=>false));

Comments

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.