Magento – Magento 2: Set Template Dynamically Using Ajax Call

controllersmagento2template

I have button in frontend. I want to change template from controller when button is clicked.

Please help me.

Best Answer

check below code.

use below code in to button click

<script type="text/javascript">
require([    
    "jquery""
    ], function ($) {
        jQuery(document).ready(function(){          
            jQuery( document ).on( 'click', 'button', function () {
                ajax();
            });         
        });         
    }); 
    function ajax(){        

            jQuery.ajax({
                    url: "<?php echo $this->getUrl('module/ajax/ajax'); ?>",
                    showLoader: true,
                    data: "",                   
                    type: 'POST'
            }).done(function(data) {



            });                     
    }
</script>

app\etc\vender\module\Controller\Ajax\Ajax.php

<?php

namespace VENDER_NAME\MODULE_NAME\Controller\Ajax;

class Ajax extends \Magento\Framework\App\Action\Action
{   

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @var \Magento\Framework\Json\Helper\Data
     */

    protected $jsonData
    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\View\Result\PageFactory resultPageFactory
     */

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

    public function execute()
    {           
            $resultRedirect = $this->resultPageFactory ->create();          
            $blockInstance = $resultRedirect->getLayout()->getBlock('module.ajax');
            $message['html'] = $blockInstance->toHtml();

            /** Json Responce */
            $this->getResponse()->representJson(
                $this->jsonData->jsonEncode($message)
            );
    }
}

app\etc\vender\module\view\frontend\layout\controllername_ajax_actionname.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>                     
        <block class="Magento\Framework\View\Element\Template" template="VENDER_MODULE::ajax.phtml" cacheable="false" name="module.ajax" as="module_ajax">

        </block>        
    </body>
</page>

app\etc\vender\module\view\frontend\templates\ajax.phtml