I have a custom module with a button in the admin that i want to call a controller class on click. My phtml file contains this JavaScript :
<script type="text/javascript">
require(["jquery"],function($) {
$('#savePricing').click(function() {
var customurl = "XX/Pricing/Controller/SaveFamilyPriceChanges";
$.ajax({
url: customurl,
type: 'POST',
dataType: 'json',
data: {},
complete: function(response) {
var status = response.responseJSON.status;
console.log(status);
},
error: function (xhr, status, errorThrown) {
console.log('Error happens. Try again.');
}
});
});
});
</script>
here is my XX/Pricing/Controller/SaveFamilyPriceChanges.php
<?php
namespace XX\Pricing\Controller;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Customer\Model\Session;
/**
* Class SaveFamilyPriceChanges
* @package XX\Pricing\Controller
*/
class SaveFamilyPriceChanges extends \Magento\Framework\App\Action\Action
{
/**
* @var JsonFactory
*/
private $resultJsonFactory;
/**
* @var Session
*/
private $customerSession;
/**
* @param JsonFactory $resultJsonFactory
*/
public function __construct(
JsonFactory $resultJsonFactory,
Session $customerSession
) {
$this->resultJsonFactory = $resultJsonFactory;
$this->customerSession = $customerSession;
}
/**
* @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Json|\Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$response = $this->resultFactory
->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON)
->setData([
'status' => "ok",
'message' => "form submitted correctly"
]);
return $response;
}
}
When i click the button i am getting :
{"error":true,"message":"Invalid Form Key. Please refresh the page."}