views:

70

answers:

1

I have a bit of data that I want to use to build a form's select field. The JS that generates the form (it's part of the jqgrid plugin) is in the view. How do I get the data from the controller into the javascript so I can use it?

To just get something working I tried the following...

In the controller I created an action to return some sample data:

public function testAction()
    {
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        $a = "0:Select";
        return Zend_Json::encode($a);
    }

In the view I make an ajax call to that action:

 var testselect = $.ajax({
     url: '/admin/sites/test',
     dataType: "json",
     complete: function(data) {
             console.log(data);
     }
 });  

And this returns an XMLHTTPRequest object that contains, in part:

responseText:""
status:200
statusText:"OK"

Shouldn't the responseText be whatever was returned by the call to /admin/sites/test?

In my mind this is what is happening:

  1. the view makes an ajax request to the test action of the sites controller in the admin module
  2. the test action JSON encodes the contents of $a and returns it
  3. the complete callback function of testselect logs the result to the console and should have the contents of $a in the responseText.

Where am I misunderstanding this? Is there a better way to do this? Like, could the controller pass the needed data to the view object and then I somehow access that in the javascript (though how, without making an ajax request or putting the data into some superglobal like $_SESSION I don't know)?

Any help is appreciated.

+2  A: 

Try this:

public function testAction() {
  $data = array('firstname' => 'Benny', 'surname' => 'Hill');
  $this->_helper->json($data);
}

See the section about the json action helper in the documentation.

You could also read up on the section about the action helpers ContextSwitch and AjaxContext

chelmertz
Thanks for those links. Just what I needed! And I approve of the Benny Hill reference.
rg88