Im trying to create an Ajax call in frontend but I get redirect to Homepage when I get to the controller. Can anyone explain why? Many thanks. Here my script in phtml
<script type="text/javascript">
require(["jquery"],function($) {
$(document).ready(function() {
var customurl = "<?php echo $block->escapeUrl($block->getUrl('webentry/index/search'))?>";
$("#search-button").on('click', function () {
$.ajax({
url: customurl,
type: 'POST',
dataType: 'json',
data: {
postCode: $('#headquarter_post_code').val()
},
success: function(response) {
console.log("Success!!");
},
error: function (xhr, status, errorThrown) {
console.log(errorThrown);
}
});
});
});
});
My controller
class Search extends \Magento\Framework\App\Action\Action {
protected $resultFactory;
public function __construct (
\Magento\Framework\App\Action\Context $context,
ResultFactory $resultFactory
) {
$this->resultFactory = $resultFactory;
parent::__construct($context);
}
public function execute()
{
$resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
$response = $this->resultFactory->create(ResultFactory::TYPE_RAW);
$response->setHeader('Content-type', 'text/plain');
$country = 'india';
$state = 'gujarat';
$response->setContents(
$this->_jsonHelper->jsonEncode(
[
'default_country' => $country,
'state' => $state,
]
)
);
return $response;
}
}