I'm using ajax in Magento 2 admin. But it not working.
My controller:
class CustomAjax extends \Magento\Backend\App\Action{
protected $resultJsonFactory;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
)
{
parent::__construct($context);
$this->resultFactory = $resultJsonFactory;
}
public function execute()
{
$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData([
'messages' => 'Successfully. Params: ',
'error' => false
]);
}
public function indexAction(){
return $this->resultJsonFactory->create()->setData(['a' => 'b']);
}}
- If I use url of jQuery ajax without
isAjax=true
it say 302 found error in response. - If I use
isAjax=true
for url ajax it sayinvalid form key...
. - When I add
form_key
:"form key value"
indata:{}
of ajax it say404 Forbidden.
Please help me, thank so much!
— update
My url in this case is
http://localhost/magento/admin/mymodule/customAjax/index/key/417a3857c3ee5d1ec2c2c474ce5ce0a217779619d313b12e0d668b950ac80d9d/?isAjax=true
and this is ajax:
jQuery.ajax({
type:"POST",
url: ajaxUrl,
data:{
form_key: formKey
},
beforeSend : function(data){
},
success : function(data){
}
});
formKey in this case is u5XSzd7EmRKQM7kN
But it say 404 Forbidden error.
Best Answer
Seem that your Ajax is missing the form key param. We need to add the form key value to url. For example:
You can see an example:
vendor/magento/module-import-export/view/adminhtml/templates/import/form/before.phtml