I am using Magento 2 i want to send an AJAX request from my custom js.
Here is the code
jQuery.ajax({
method: "POST",
url: "app/code/Preview/Tag/Block/Baz/getTitle",
data: {data: doc.output()},
}).done(function(data){
console.log(data);
});
But it returns 403 forbidden.
Please let me know what is causing the issue.
Controller code:
root_dir/app/code/Preview/Tag/Block/Baz.php
<?php
namespace Preview\Tag\Block;
/**
* Baz block
*/
class Baz extends \Magento\Framework\View\Element\Template
{
public function getTitle()
{
return "Foo Bar Baz";
}
}
?>
URL you are using is wrong , you need to learn about Magento2 Structure before you start code in Magento2.
what you are using is a Block not a Controller,
1st you need to define a route in file etc/frontend/routes.xml
<?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="previewtag" frontName="previewtag">
<module name="Preview_Tag" />
</route>
</router>
</config>
than after you need to define Controller file Controller/Index/Index.php
<?php
namespace Preview\Tag\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
public function execute()
{
// your code here
echo "Foo Bar Baz";
}
}
now you can use the URL as
previewtag/index/index
or previewtag
both works same
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.