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
Pinku
5371 gold badge11 silver badges25 bronze badges
-
magento.stackexchange.com/questions/128669/… or magento.stackexchange.com/questions/130372/…Jackson– Jackson2017年01月10日 06:46:06 +00:00Commented Jan 10, 2017 at 6:46
default