2

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).

  • did the problem resolved? – Amit Bera Oct 26 '16 at 15:25
  • No it did not. I try to ask again. – user3748173 Oct 26 '16 at 15:26
2

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.