How to Update a Widget Using AJAX

ajaxcontrollerswidgets

I am adding a widget to a CMS page. Within this widget will be some ajax calls — however, i'm unsure what / how I should call this layout block in the controller to update the frontend code.

The widget is located here:

magento/app/design/frontend/enterprise/default/template/catalog/product/widget/new/content/new_grid.phtml

In the CMS page I can calling the widget as such:

{widget type="catalog/product_widget_new" display_type="new_products"
show_pager="1" products_per_page="20" products_count="1000"
template="catalog/product/widget/new/content/new_grid.phtml"}

The ajax calling function will look something like:

newPerPage = function (value) {
    try {
        jQuery.ajax({
            url: url,
            dataType: 'json',
            type: 'post',
            data: value,
            success: function (data) {
                jQuery('#product-grid-category').html(data.field);
            }
        });
    } catch (e) {
    }
};

The ajax conotroller function will look something like:

public function newPagerAction(){
    $this->setData('products_per_page', param);
    $response = array();
    $response['field'] = $this->getLayout()->createBlock('....')->setTemplate('....')->toHtml();
    $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
}

Best Answer

Try this in your controller:

public function couponPostAction()
{
    if (!$this->getRequest()->isAjax()) {
        $this->_forward('noRoute');
        return;
    }

    $block = $this->getLayout()->createBlock('catalog/product_widget_new', 'product.widget.new', array(
        'show_pager'        => 1,
        'products_per_page' => 24,
        'products_count'    => 1000,
        'display_type'      => 'new_products',
        'template'          => 'catalog/product/widget/new/content/new_grid.phtml'
    ));

    $this->getResponse()->setBody(
        Mage::helper('core')->jsonEncode(array(
            'field' => $block->toHtml()
        ))
    );
}