Magento - Load products by ajax in current template design

Magento - Load products by ajax in current template design

July 13, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Magento - Load products by ajax in current template design

Magento - Dynamically Load Products by AJAX within the Current Theme

As a developer working on a Magento extension, you may find yourself needing to dynamically load products using AJAX while maintaining the current theme’s design. In this blog post, we’ll explore how to achieve this efficiently without relying on built-in extensions or static HTML/CSS from the base theme.

The Current Approach and Challenges

You’ve already implemented an AJAX function that sends a request to your controller with the category ID:

function loadCategoryProducts(categoryId) {
    jQuery.ajax({
        url: '/myModule/index/loadcategoryproduct',
        type: 'post',
        data: { categoryId: categoryId },
        success: function (products) {
            // ... parse and create HTML from the AJAX response ...
            jQuery('.col-main').html(html);
        }
    });
}

Your controller successfully retrieves products based on the provided category ID:

public function loadcategoryproductAction() {
    $id = $this->getRequest()->getParam('categoryId');
    if ($id) {
        // ... fetch and format product data ...

        $json_products = array();
        foreach ($_productCollection as $_product) {
            $json_products[] = array(
                'name' => $_product->getName(),
                'url' => $_product->getProductUrl(),
                'description' => nl2br($_product->getShortDescription()),
                'price' => $_product->getFormatedPrice(),
                'image' => $_product->getImageUrl()
            );
        }

        $data = json_encode($json_products);
        echo $data;
        die;
    }
}

While this approach works, it has a significant limitation: the rendered HTML is static and relies on the base theme’s design. If the store’s theme is changed, your extension will no longer display products properly.

A Better Approach: Leveraging Magento’s Layout System

To solve this problem, we need to leverage Magento’s layout system to render the dynamically loaded products within the current active theme. Here’s how you can achieve this:

  1. Create a new block for product listing: In your extension, create a new block (e.g., My_MyModule_Block_CategoryProducts) that will hold the list of category products.

  2. Render the block in your layout XML file: Update your layout XML file (e.g., app/design/frontend/{package}/{theme}/layout/my_module.xml) to include a new reference for your product listing block:

<reference name="content">
    <block type="my_mymodule/category_products" name="category-products" template="mymodule/category/products.phtml"/>
</reference>
  1. Create the PHTML template: In the PHTML template file (e.g., app/design/frontend/{package}/{theme}/template/mymodule/category/products.phtml), you can use Magento’s built-in template functionality to display the products:
<?php foreach ($_products as $_product): ?>
    <div class="category-products">
        <h2><?php echo $this->escapeHtml($_product['name']) ?></h2>
        <p><?php echo nl2br($this->escapeHtml($_product['description'])) ?></p>

        <a href="<?php echo $this->escapeHtml($_product['url']) ?>"><?php echo $this->escapeHtml($_product['name']) ?></a>
    </div>
<?php endforeach; ?>
  1. Update your controller to return the block: Modify your controller action to return the product listing block instead of a JSON response:
public function loadcategoryproductAction() {
    $id = $this->getRequest()->getParam('categoryId');

    if ($id) {
        // ... fetch and format product data ...

        $_products = $json_products;

        $block = Mage::app()->getLayout()->createBlock('my_mymodule/category_products');
        $block->setData('products', $_products);
        $block->setTemplate('mymodule/category/products.phtml');

        $output = $block->toHtml();

        echo $output;
        die;
    }
}
  1. Update your AJAX function: Finally, update your JavaScript function to append the returned HTML to the desired container:
function loadCategoryProducts(categoryId) {
    jQuery.ajax({
        url: '/myModule/index/loadcategoryproduct',
        type: 'post',
        data: { categoryId: categoryId },
        success: function (html) {
            jQuery('.col-main').append(html);
        }
    });
}

Conclusion

By leveraging Magento’s layout system and creating a dedicated block for product listing, you can now dynamically load products using AJAX within the current active theme. This approach ensures that your extension remains compatible with various themes without relying on static HTML/CSS from the base theme.

Remember to replace {package} and {theme} in the example XML file paths with your actual package name and theme name. Also, ensure that you have created the necessary directories for your template files if they don’t exist already.

With this solution, you can create a more versatile extension that adapts seamlessly to different Magento themes while maintaining the original design and functionality of each theme. For further insights into Magento development best practices, feel free to explore our Magento Developer Resources at Laravel Company.

Happy coding!

Catalog Database Extensions Themes

Our network