Magento – Update view.phtml ajax call

ajaxmagento-1module

I have a problem updating catalog/product/view.phtml with AJAX.
What I'm trying to do is get the selected value from a custom dropdown in view.phtml and then filter all the products that have a certain attribute equal to the selected option from the dropdown.

Here's my code:
(I've activated correctly the module with the Yui_Filterajax.xml in app/etc/modules.)

View.phtml:

function getCustomAtt() {
    var selection = jQuery('.selectAttr').val(); //Gets the value of dropdown
    jQuery.ajax({
        url: "<?php echo $this->getUrl('filterajax/ajax/index') ?>",
        type: "POST",
        data: { myval: selection},
        success: function(data) {
            console.log('success')
            console.log(data);
        }
    });
}

app/code/local/Yui/Filterajax/controllers/AjaxController.php

class Yui_Filterajax_AjaxController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
        $this->loadLayout();
        $this->renderLayout();
    }
}

app/code/local/Yui/Filterajax/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Yui_Filterajax>
            <version>0.1.0</version>
        </Yui_Filterajax>
    </modules>
    <frontend>
        <routers>
            <filterajax>
                <use>standard</use>
                <args>
                    <module>Yui_Filterajax</module>
                    <frontName>filterajax</frontName>
                </args>
            </filterajax>
        </routers>
        <layout>
            <updates>
                <filterajax>
                    <file>filterajax.xml</file>
                </filterajax>
            </updates>
        </layout>
    </frontend>
</config>

app/design/frontend/MyTheme/default/layout/filterajax.xml

<?xml version="1.0"?>
<layout version="1.0">
    <filterajax_ajax_index>
        <block type="filterajax/filterajax" name="root" output="toHtml" template="catalog/product/view.phtml" />
    </filterajax_ajax_index>
</layout>

The problem is, that in the console I see the text 'success' and this error:

Cannot send headers; headers already sent in
../magento/app/code/local/Yui/Filterajax/controllers/AjaxController.php,
line 19

So I can't get the result. I don't know what to try…

Best Answer

Try this

<?php
class Yui_Filterajax_AjaxController extends Mage_Core_Controller_Front_Action
{           
    public function indexAction()
    {    
        // Do your stuff  here
        $this->loadLayout();
        // root  as per your layout file
        $block  = $this->getLayout()->getBlock('root')->toHtml();                  
        $this->getResponse()->setBody($block);
        return; 
    }
}
Related Topic