Magento – Pass Variable from AjaxController to Block Class

ajaxblocks

hi i have an AjaxController

<?
class TEST_Productstab_AjaxController extends Mage_Core_Controller_Front_Action {

    public function indexAction() {


        $type = $this->getRequest()->getParam('type');
        $cat = $this->getRequest()->getParam('cat');

        //i have to pass $type and $cat to block class, anything like setData($type), so i can save the value?

    }
}
?>

and a block class

<?php
class TEST_Productstab_Block_Productstab extends Mage_Core_Block_Template
{
   public function methodBlock()
   {
     //i have to get $type and $cat in this class, anything like getData($type), so i can get teh value here?

     echo $type."<BR>";
     echo $cat;
   }
}
?>

How can i pass $type & $cat to methodBlock function , so i can print the output by calling $this->methodBlock() in phtml

thanks

Best Answer

Magento Support Team is correct, but it's not quite a complete answer - in your controller you need to first load the layout:

$this->loadLayout();

now you can get your block and set a value:

$this->getLayout()->getBlock('yourblockname')->setValue($somevar);

and finally render it out:

$this->renderLayout();

in your block you can then:

$this->getValue();

which will return $somevar.

The other alternative is to set a registry value in your controller:

Mage::register('name', $value);

and retrieve it in your block:

Mage::registry('name');

you can delete the registry value with:

Mage::unregister('name');

note that if you try to register a value that already exists an exception will be thrown so if in doubt unregister before you register (you can unregister a non existent registry value without causing issues).

With an AJAX request you are either going to want to set the response body in your controller to determine what is returned in the responseText:

$this->getResponse()->setBody('some repsonse');

or you are going to want to replace the root block in your layout with just your block in the layout so that the response doesn't contain common areas like header, footer and sidebar and instead just contains your blocks content (this way you don't need to set the response body in the controller):

<?xml version="1.0"?>
<layout version="0.1.0">
    <frontname_controller_action>
        <block type=module/block" name="root" template="module/template.phtml" />
    </frontname_controller_action>
</layout>

If you do it this way, you just need to ->getBlock('root') in the controller when pulling the block to set a value against it.

EDIT: As a side note, you shouldn't be closing your PHP classes with ?> - see here