Magento – Magento 2 layout with no html head or body tags for ajax output

ajaxlayoutmagento2page-layouts

I'm attempting to output the wishlist block as an ajax request. I've attempted to do it in the controller using

$block = $resultPage->getLayout()
->createBlock('Magento\Wishlist\Block\Customer\Wishlist','miniwishlist')            
->setTemplate('Company_Module::miniwishlist.phtml')
->toHtml();

But as the block contains several child blocks and I didn't have any success in using the setChild method programmatically.

I've since created a layout file that returns the block by itself. The problem is that output contains html, head, body tags, css and javascript.

I want to return only the block and nothing else. How can I achieve that?

Best Answer

I went about it differently, but got the result I was after, with very little modification.

I access the contents of the wishlist block using a modified url http://domain.com/wishlist/index/index/ajax/1

I've appended the 'ajax/1' to the normal wishlist request

In my module I overwrote the block \Magento\Wishlist\Block\Customer\Wishlist and modified the function _toHtml as follows:

protected function _toHtml()
{
    if ($this->currentCustomer->getCustomerId()) {
        if ($this->getRequest()->getParam('ajax')) {
            die(parent::_toHtml());
        }
        else return parent::_toHtml();
    } else {
        return '';
    }
}

I also had to add the template file View.phtml to my module, which works nicely as I am able to modify that to get the desired output for my ajax call.

Related Topic