I am trying to make my first ajax request in magento to controller file but can not get it working. My .js file is:
jQuery.ajax({
type: 'post',
url: 'vendor_module/index/htmlcreator',
data: {key: variable},
dataType: 'json'
}).done(function (msg) {
var variable = "Data Saved: " + msg;
return variable;
});
My Controller file:
class htmlCreator extends \Magento\Framework\App\Action\Action{
public function __construct(
Context $context, \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory) {
$this->resultJsonFactory = $resultJsonFactory;
parent::__construct($context);
}
public function execute() {
$result = $this->resultJsonFactory->create();
if ($this->getRequest()->isAjax()) {
$test = '<h1>Hello World</h1>';
return $result->setData($test);
}
}}
What is the controller files url? If it contains domain name how can i find it in js file? What would be the securest way to write url? I prefer not to use phtml file, unless I really need to (security).
Best Answer
If you data from
vendor_module/index/htmlcreator
the you need below files:Controller files location should be app/code/[Vendor]/[Module]/Controller/Index/ and file name should be
Htmlcreator.php
.In magento, a url have
1 part
is frontName.Herevendor_module
isfrontName
for your module.So,you need define that frontName usingroutes.xml
which located at app/code/[Vendor]/[Module]/etc/frontend/