Magento 2 – jQuery Ajax Data to Controller

ajaxjavascriptjquerymagento2url

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.Here vendor_module is frontName for your module.So,you need define that frontName using routes.xml which located at app/code/[Vendor]/[Module]/etc/frontend/

<?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="vendor_module" frontName="vendor_module">
            <module name="[Vendor]_[Module]" />
        </route>
    </router>
</config>