Magento – Ajax not working in Magento 2 admin

admin-controlleradminhtmlajaxmagento2

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 say invalid form key....
  • When I add form_key: "form key value" in data:{} of ajax it say 404 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:

var form = jQuery('#edit_form');
var action = form.attr('action');

//Assume your form action form.attr('action'): http://{admin_url}/custom/ajax/key/f7f0ad18f378d5458e936d216981f1418702a8381da453a094b6273410f2eb0e/

var newActionUrl = action + '?' + encodeURIComponent(form.find('[name="form_key"]').val());

You can see an example: vendor/magento/module-import-export/view/adminhtml/templates/import/form/before.phtml