1

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.

asked Jan 10, 2017 at 6:44
1

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.