0

I am working on one custom module and i need product load when any ID is clicked. Loading is handle by ajax. I am not aware of ajax in Magento 2. Can anybody give me small demo of ajax in Magento 2

Controller file

namespace Vendor\Modulename\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\Controller\ResultFactory;



class Index extends Action
{
    /**
     * @var \Tutorial\SimpleNews\Model\NewsFactory
     */
    protected $resultJsonFactory;
    protected $resultPageFactory;

/**
 * @param Context $context
 * @param NewsFactory $modelNewsFactory
 */



public function __construct(
        Context                                             $context,
        \Magento\Framework\Controller\Result\JsonFactory    $resultJsonFactory,
        PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->resultJsonFactory            = $resultJsonFactory;
        parent::__construct($context);
    }


   public function execute()
    {
        /*Put below your code*/
        // $id = $this->getRequest()->getPost('id', false);
        $responseData = $this->resultJsonFactory->create();
        $resultJson = $this->resultPageFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData($responseData);
        return $resultJson;
    }
}

router file

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="modulename" frontName="modulename">
            <module name="Vendor_ModuleName" />
        </route>
    </router>
</config>

Template file

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

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

    }); 
</script>

Js file

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){
                    alert(response);
                }
            });
        });
    }
}

});

The above code is not working. It's showing error.

Your Answer

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

Browse other questions tagged or ask your own question.