1

Can any one give me an example of Displaying Random Products on homepage using AJAX in Magento 2.3

  • What is your current state of the project, can you share some code? – Felix Schönherr Aug 23 at 6:32
  • +1 for answer acceptance :) – Shoaib Munir Aug 24 at 5:07
1

create a module and call it's controller function using ajax and assign value in a div

<div class="products wrapper grid random_products" style="display:none;">
    <ol class="products list items product-items row row-wrapper row-5"></ol>
</div>

<script>
require([
    'jquery'
], function($){
    jQuery.ajax({
        url: "/yourcontrollerurl",
        type: "GET",
        data: "",
        success: function (res) {
            if(res.indexOf("find products matching the selection") > -1){
                return;
            }
            var result = jQuery('.product-items', res).html();
            jQuery(".random_products").show();
            jQuery(".random_products.product-items").html(result);
        }
    });
});
</script>

Now in your controller use this:

protected $resultPageFactory;
public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\View\Result\PageFactory $resultPageFactory
)
{
    $this->resultPageFactory = $resultPageFactory;
    return parent::__construct($context);
}

public function execute()
{
    //Default message if validation failed.
    $block = "<div class=\"message info empty\"><div>We can't find products matching the selection.</div></div>";

    //Getting products list if validation passed

    $viewBlock = $this->resultPageFactory->create();
    $block = $viewBlock->getLayout()
        ->createBlock('Vendor\Module\Block\ProductList')
        ->setTemplate('Magento_Catalog::product/list.phtml')
        ->toHtml();


    //Setting response
    $this->getResponse()->setBody($block);
}

Now create ProductList.php block app/code/Vendor/Module/Block/ProductList.php

<?php

namespace Vendor\Module\Block;

use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Model\Layer\Resolver;
use Magento\Framework\Data\Helper\PostHelper;
use Magento\Framework\Url\Helper\Data;

class ProductList extends \Magento\Catalog\Block\Product\ListProduct
{
    protected $collection;
    protected $visibility;

    public function __construct(
        Context $context,
        PostHelper $postDataHelper,
        Resolver $layerResolver,
        CategoryRepositoryInterface $categoryRepository,
        \Magento\Catalog\Model\ResourceModel\Product\Collection $collection,
        \Magento\Catalog\Model\Product\Visibility $visibility,
        Data $urlHelper,
        array $data = []
    )
    {
        $this->collection = $collection;
        $this->visibility = $visibility;
        parent::__construct($context, $postDataHelper, $layerResolver, $categoryRepository, $urlHelper, $data);
    }

    protected function _getProductCollection()
    {
        if ($this->_productCollection === null) {
            $limit = 30;
            //Getting configuration
            $this->collection->addAttributeToSelect('*');
            //Enable filter
            $this->collection->addAttributeToFilter(
                'status', array('eq' => \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
            );

            //Stock filter
            $this->collection->joinField(
                'qty', 'cataloginventory_stock_item', 'qty', 'product_id=entity_id', '{{table}}.stock_id=1', 'left'
            );

            $this->collection->setVisibility($this->visibility->getVisibleInSiteIds());

            //Setting up pagination
            $this->collection->setPageSize($limit)
                ->setCurPage(1);

            //This will sort in random order
            $this->collection->getSelect()->orderRand();
        }

        $this->_productCollection = $this->collection;

        return $this->_productCollection;
    }
}
  • In which file we need to write the script? – Nafisa Aug 23 at 6:45
  • you can write in any file on home page where you need random products – Shoaib Munir Aug 23 at 6:45
  • answer updated, script was not correct before. It's fine now – Shoaib Munir Aug 23 at 6:47
  • we can write this in phtml file? – Nafisa Aug 23 at 6:50
  • yes in .phtml file – Shoaib Munir Aug 23 at 6:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.