tags:

views:

1360

answers:

1

Hello,

I am trying to use ajax call with Magento. When I call a block page via Ajax, I get all the HTML including head, css, javascript, and body. How do I get only body part?

+5  A: 

If you can provide a little more information about which "block page" you are calling it may be easier to discern the issue. By default, Magento includes the <default> layout tag for all pages, which will give you the page headers and footers even on AJAX calls.

To send a page without all that extra, you have a few options. Firstly, you can simple set the output manually on your own, avoiding the layout system entirely. Magento does this for the one-page checkout feature:

$result = array( 'foo' => 'foo', 'bar' => 'bar', );
$this->getResponse()->setBody(Zend_Json::encode($result));

You can also modify this method to use a custom layout handler like this:

protected function loadPage() {
    $layout = $this->getLayout();
    $update = $layout->getUpdate();
    $update->load('your_custom_handle');
    $layout->generateXml();
    $layout->generateBlocks();
    $output = $layout->getOutput();

    $result = array( 'outputHtml' => $output, 'otherVar' => 'foo', );
    $this->getResponse()->setBody(Zend_Json::encode($result));        
}

And in your layout file:

<your_custom_handle>
    <remove name="right"/>
    <remove name="left"/>

    <block type="module/block" name="root" output="toHtml" template="module/template.phtml"/>
</your_custom_handle>

A second option, if you want to use layouts, is to define an alternative default layout. When you call $this->loadLayout(); in Magento controllers, you can actually specify a handle other than <default> to descend from. An example from the Magento product controller would be:

$this->loadLayout('popup');

This layout is defined by default within the main.xml layout file, and renders the popup.phtml template, and may be suitable for your use.

If you still have trouble, let me know and we can try other things. Hope that helps.

Thanks, Joe

Joseph Mastey
Thank you for this. Saved me a heap of time.
Travis
Note that if your copying and pasting the layout file example, make sure to change `type="module/block"` to an actual magento block type, like `type="page/html"`, or a custom block type defined for you module.
zlovelady