Friday, January 10, 2014

Magento: Use ajax filter in magento catalog

There are two things need to do
1.Convert all request into ajax request using following script

function filter(){
    jQuery('.toolbar a').each(function(index){
        jQuery(this).click(function(){
            filterAjax(jQuery( this ).attr('href'));          
            console.log( index + ": " + jQuery( this ).text() ); return false;
        });
     
    });
    jQuery('.toolbar select').each(function(index){
        jQuery(this).removeAttr('onchange');
        jQuery(this).change(function(){
            filterAjax(jQuery( this ).val());
            console.log( index + ": " + jQuery( this ).text() ); return false;
        });
     
    });
    jQuery('.block-layered-nav a').each(function(index){
        jQuery(this).click(function(){        
            filterAjax(jQuery( this ).attr('href'));
            console.log( index + ": " + jQuery( this ).text() ); return false;
        });
     
    });
}
function filterAjax(s_url){
    jQuery('#loader').show();
    jQuery.ajax({
            type: "GET",
            //data : {is_ajax:1},
            url: s_url,
            success: function(data) {
            jQuery('.category-products').remove();
            jQuery('.col-main').append(data.page);                  
            jQuery('.block-layered-nav').remove();
            jQuery('.col-left').prepend(data.block);
            //jQuery('body').append(data.js);
            jQuery('#loader').hide();
            filter();
      }
    });
}
jQuery(document).ready(function(){
    filter();
});

2. Then convert output into JSON using following script

$layout = Mage::getSingleton('core/layout');
if (!$layout)
return;
if (!Mage::app()->getRequest()->isXmlHttpRequest())
return;          
$layout->removeOutputBlock('root');  
Mage::app()->getFrontController()->getResponse()->setHeader('content-type', 'application/json');

$page = $layout->getBlock('product_list');
if (!$page)
return;
$block='';
foreach ($layout->getAllBlocks() as $child){              
if (!in_array($child->getNameInLayout(), array('catalog.leftnav'))){
    continue;
}
$block = $child;
}
if (!$block)
return;      
$container = $layout->createBlock('core/template', 'sparx_container');
//$container->setData('js', $layout->createBlock('core/template', 'ajaxfilter_js')->setTemplate('ajaxfilter/js.phtml')->toHtml());
$container->setData('block', $block->toHtml());
$container->setData('page', $page->toHtml());
$layout->addOutputBlock('sparx_container', 'toJson');

Here we have to use event observer concept.
(controller_action_layout_render_before_catalog_category_view)



No comments:

Post a Comment