Magento 2 – How to Create Custom Action in Controller for Ajax Call

ajaxcontrollersmagento2

How Do I create my own Action in Controller to call url from Ajax in Magento 2.0.

Like in Magento 1.9 we can create any Action an any Controller and call that from URL.

Best Answer

You can use the code below your own Action in controller to call url from Ajax. Using phtml file.

In your (Like vendor/module/Block/Example.php) block put below code.

public function getAjaxUrl(){
    return $this->getUrl("module/index/view"); // Controller Url
}

Put below code view/fronted/templates/example.phtml

<script>
    require(
        ['jquery','example'],
        function($,example){

        var ajaxurl = '<?php echo $block->getAjaxUrl() ?>';
        example.exampleData(ajaxurl);

    }); 
</script>

Put below code view/fronted/web/js/example.js

define([
        'jquery',
        ],
    function($,example){

    return {
        exampleData:function(ajaxurl){
        $(document).on('click','.example-list',function (event){
                event.preventDefault();
                var id=$(this).attr('id');
                $.ajax({
                    url:ajaxurl,
                    type:'POST',
                    showLoader: true,
                    dataType:'json',
                    data: {id:id},                                      
                    success:function(response){
                        //put your code
                    }
                });
            });
        }
    }

});

Your own controller like vendor/module/Controller/Index/View.php

<?php

namespace Vendor\Module\Controller\Index;

use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Context;
use Vendor\Module\Model\ResourceModel\Example\CollectionFactory;

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

    protected $resultPageFactory;

    public function __construct(
        Context $context,
        CollectionFactory $exampleFactory,
        PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->exampleFactory = $exampleFactory;
        parent::__construct($context);
    }
    /**
     * Index action
     *
     * @return $this
     */
    public function execute()
    {
        /*Put below your code*/
        $id = $this->getRequest()->getParam('id', false);
        $responseData = $this->exampleFactory->create();

        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData($responseData);
        return $resultJson;
    }
}