How can I call my custom controller through javascript? Any way by which I can pass the url of controller and call that with "parameter"?
2 Answers
Can you share your js, if you use an jquery widget you can pass the url as options But if you have a simple js you can define your car in phtml
<script>
var url = '<?php echo $this->getUrl('test'); ?>'
</script>
-
"vendor/mymodule/controller/module/index" how to pass this as a full url?akshay billore– akshay billore2017-11-10 14:02:03 +00:00Commented Nov 10, 2017 at 14:02
-
<?php echo $this->getUrl('mymodule/module'); ?>'Mohamed El Mrabet– Mohamed El Mrabet2017-11-22 20:12:05 +00:00Commented Nov 22, 2017 at 20:12
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
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;
}
}
Hope this will help.