0
votes

I tried this in the layout file

$(document).ready(function(){ alert("hello"); } );

How do I get this simple thing working? I included jquery in the layout file, using echo $this->headScript()->appendFile(....)

Is there a way to use jquery as is? Without using zendx?

2
Why don't you use a separate file for the javascript? - sica07
You don't need to use ZendX, can you provide code to show how you attempted to do it. - piddl0r
I included jquery in my layout file, using headScript()->appendFile(..). In the layout file, in head tag, inside the script tag, I put the above code (an alert inside document ready). What am I doing wrong? :( - user187809

2 Answers

3
votes

What about the following in your layout file:

$this->headScript()->appendFile('/js/jquery.js'); 
$this->headScript()->appendScript('$(document).ready(function() { alert("hello"); });','text/javascript');

What I mostly do is:

$this->headScript()->appendFile('/js/jquery.js');
$this->headScript()->appendFile('/js/application.js');
$this->headScript()->appendScript('application.init();', 'text/javascript');

echo $this->headScript();

Then the application.js:

var application = {
  init : function() {
    //do here anything you like
  }
}

If you want to call a specific function from let's say your controller you add this function to your application JS first:

var application = {
  init : function() {
    //do here anything you like
  },
  bindChangeEventToSomething : function() {
    $('a').click(function() {});
  }
}

Then in your controller you could add in your action:

$this->view->headScript->appendScript(
   'application.bindChangeEventToSomething()',
   'text/javascript'
);
1
votes

You should be able to include jQuery without using ZendX. If you would like it to be included in every page add it in the bootstrap or in a controller if it's specific. Here's an example of what putting it in the bootstrap would look like :

protected function _initView(){
    $this->bootstrap('layout');
    $layout = $this->getResource('layout');
    $view = $layout->getView();
    $view->headScript()->appendFile('/js/jquery.min.js');
}

If you wish to include a js file in just a single controller/action you can include it the init/action of the controller.

$this->view->headScript()->appendFile('/js/index.js');