cancel
Showing results for 
Search instead for 
Did you mean: 

Magento 2: Custom added ajax pagination not working

Magento 2: Custom added ajax pagination not working

I have added an ajax pagination in a custom module collection. I have a total of 50 items in the collection and the limit per page is 5; that should show total page of 10.

Instead, it is showing only 5 pages, it is not showing the next page Link either and there is no active clickable page link.

 

When I click on 5 (number page) or Next arrow should display next page like 6 7 8 etc but it does not

I have followed the File path Below to implement This pagination.

 

Step 1: Block file code.

 

File path: app/code/Vendor/Module/Block/Test.php

public function getPagerHtml()
    {
        if ($this->getLayout()->getBlock('test.page.pager')) {
            $this->pager = $this->getLayout()->getBlock('test.page.pager');
    
            return $this->pager->toHtml();
        }
        if (!$this->pager) {
            $this->pager = $this->getLayout()->createBlock(
                Pager::class,
                'test.page.pager'
            );
    
            if ($this->pager) {
                $this->pager->setUseContainer(
                    false
                )->setShowPerPage(
                    false
                )->setShowAmounts(
                    false
                )->setFrameLength(
                    $this->_scopeConfig->getValue(
                        'design/pagination/pagination_frame',
                        \Magento\Store\Model\ScopeInterface::SCOPE_STORE
                    )
                )->setJump(
                    $this->_scopeConfig->getValue(
                        'design/pagination/pagination_frame_skip',
                        \Magento\Store\Model\ScopeInterface::SCOPE_STORE
                    )
                )->setLimit(5)->setCollection(
                    $this->getLocationCollection()
                );
    
                return $this->pager->toHtml();
            }
        }
    
        return '';
    }
    
    public function getLocationCollection()
    {
        $pageNumber = (int)$this->getRequest()->getParam('p') ? (int)$this->getRequest()->getParam('p') : 1;
        if (!$this->itemCollection) {
            $this->itemCollection = $this->itemCollectionFactory->create();
        }
        $this->itemCollection->setCurPage($pageNumber);
        $this->itemCollection->setPageSize(5);
    
        return $this->itemCollection;
    }
    
    protected function _prepareLayout()
    {       
          
        $this->getPagerHtml();
    
        if ($this->pager && !$this->pager->isFirstPage()) {
            $this->addPrevNext(
                $this->getUrl('testpage/index/ajax', ['p' => $this->pager->getCurrentPage() - 1]),
                ['rel' => 'prev']
            );
        }
        if ($this->pager && $this->pager->getCurrentPage() < $this->pager->getLastPageNum()) {
            $this->addPrevNext(
                $this->getUrl('testpage/index/ajax', ['p' => $this->pager->getCurrentPage() + 1]),
                ['rel' => 'next']
            );
        }
    
    
        return parent::_prepareLayout();
    }
    
     /**
     * Add prev/next pages
     *
     * @param string $url
     * @param array $attributes
     *
     */
    private function addPrevNext($url, $attributes)
    {
        $this->pageConfig->addRemotePageAsset(
            $url,
            'link_rel',
            ['attributes' => $attributes]
        );
    }

 

Step 2: Controller file.

 

File path: app/code/Vendor/Module/Controller/Index/Ajax.php

public function execute()
    {
        $params = $this->getRequest()->getParams();
        $storeId = $this->storeManager->getStore()->getId();
    
        if(isset($params['pageNo'])){
            $pageNo = $params['pageNo'];
        }else{
            $pageNo = 1;
        }
    
        $collection = $this->collectionFactory->create()
                    ->addFieldToFilter('is_active', 1)
                    ->addStoreFilter($storeId)
                    ->setPageSize(5) 
                    ->setCurPage($pageNo); 
    
        $data = $this->prepareData($collection->getData());
        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData($data);
        return $resultJson;
    }

Step 3: Template file.

 

File path: app/code/Vendor/Module/view/frontend/templates/pagetest.phtml

 

<?php  if ($pager = $block->getPagerHtml()): ?>
        <div class="testpage-pager-container"><?= /** @escapeNotVerified */ $pager; ?></div>
    <?php endif;  ?>

Step 4: JS file code.

 

File path: app/code/Vendor/Module/view/frontend/web/js/testpage.js

 

$(".testpage-pager-container li a").live('click', function(event) {
        event.preventDefault();
    
        var pagignationUrl= $(this).attr('href'); 
        var pageSplit = pagignationUrl.split('/');
        var pageNo = pageSplit[pageSplit.length - 2];  
        $.ajax({
            url : self.options.ajaxUrl,
            type: self.options.method,
            dataType: 'json',
            data: {pageNo: pageNo},
            showLoader: true,
            beforeSend: function() {
            },
            success : function(res) {  
               $('#items-list').html(res);
            },
            error : function(request,error)
            {
                alert("Error");
            }
        });
    
    });

Any help would be appreciated. Thanks.

 

pagination.png

4 REPLIES 4

Re: Magento 2: Custom added ajax pagination not working

Hello @kirtinariya 

 

I think it's because you've set page limit  to 5 in app/code/Vendor/Module/Block/ Test.php in getPagerHtml function, please remove

 

->setLimit(5)

or change it to 10 if it throws any error.

 

Problem Solved ? Click on 'Kudos' & Accept as Solution ! Smiley Happy

Re: Magento 2: Custom added ajax pagination not working

Hello @gaurav_harsh1  I have checked to change limit to 

->setLimit(10)

but same issue.

Re: Magento 2: Custom added ajax pagination not working

@kirtinariya 

 

For debugging, change ->setPageSize(5)  to ->setPageSize(7) & ->setLimit(7) to ->setLimit(7) and check what are the changes you're seeing , after changing values, Please run :

php bin/magento cache:flush

if you're getting 7 pages then it must issue in that code there.

Problem Solved ? Click on 'Kudos' & Accept as Solution ! Smiley Happy

Re: Magento 2: Custom added ajax pagination not working

Hello @gaurav_harsh1 

I have checked  to  

->setPageSize(5)  to ->setPageSize(7) & ->setLimit(5) to ->setLimit(7) 

But not fixed issue. After change 7 to showing 7 records per page.