Invalid Form Key in Ajax Request – Magento 2.3 Admin Panel

adminadmin-panelajaxmagento2.3

I have Magento 2.3 installed, and I'm trying to create a small form in sales_order_view.xml and saving the form using ajax.

Following is the code

XYZ/Sales/view/adminhtml/layout/sales_order_view.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="order_additional_info">
            <block class="XYZ\Sales\Block\Adminhtml\Order\View\XYZBlock" name="sales_order_view_xyz" template="order/view/xyz.phtml" after="-"/>
        </referenceContainer>
    </body>
</page>

XYZ/Sales/Block/Adminhtml/Order/View/XYZBlock.php

<?php
namespace XYZ\Sales\Block\Adminhtml\Order\View;

use \Magento\Backend\Block\Template;
class XYZBlock extends \Magento\Backend\Block\Template
{

    public function getAjaxUrl()
    {
        $this->getUrl('itdsaleslocation/storelocation/index');
    }

}

XYZ/Sales/view/adminhtml/templates/order/view/xyz.phtml

<div id="order_history_block" class="edit-order-comments">
        <div class="order-history-block" id="history_form">

            <div class="admin__field">
                <label for="somefield" class="admin__field-label">
                    <?= /* @noEscape */ __('Some Field') ?>
                </label>
                <div class="admin__field-control">
                    <input  name="somefield"
                            type="text"
                            id="somefield"
                            class="input-text admin__control-text"/>
                </div>
            </div>

            <div class="admin__field">
                <div class="order-button-actions">
                    <div id="submit-button"
                         class="action-default scalable action-save action-secondary"
                        style="cursor: pointer"
                    >
                        Save
                    </div>
                </div>
            </div>
        </div>
</div>

<script type="text/javascript">
    require([
        "jquery"
    ], function($){
        $('#submit-button').on('click',function(){  
            $.ajax({
                url:"'" + <?php echo $block->getAjaxUrl(); ?> + "'",
                success: function(response){
                    console.log(response);
                }
            });
        });
    });
</script>

XYZ/Sales/etc/adminhtml/routes.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
        <route id="itdsaleslocation" frontName="itdsaleslocation">
            <module name="XYZ_Sales"/>
        </route>
    </router>
</config>

XYZ/Sales/Controller/Adminhtml/StoreLocation/Index.php

<?php

namespace XYZ\Sales\Controller\Adminhtml\StoreLocation;

use Magento\Backend\App\Action;

class Index extends Action
{
    public function __construct(Action\Context $context)
    {
        parent::__construct($context);
    }

    public function execute()
    {
        $arr = array();
        $arr[0] = 'hello';

        echo json_encode($arr);
    }
}

When I click the save button I get the response as

enter image description here

How to submit ajax successfully?

Best Answer

Please try to update below your script code :

<script type="text/javascript">
    require([
        "jquery"
    ], function($){
        $('#submit-button').on('click',function(){  
            $.ajax({
                url:"'" + <?php echo $block->getAjaxUrl(); ?> + "'",
                data: {form_key: window.FORM_KEY},
                type: 'POST'
                success: function(response){
                    console.log(response);
                }
            });
        });
    });
</script>

---> XYZ/Sales/Controller/Adminhtml/StoreLocation/Index.php

<?php

namespace XYZ\Sales\Controller\Adminhtml\StoreLocation;

use Magento\Backend\App\Action;

class Index extends Action
{
    protected $resultJsonFactory;
    public function __construct(Action\Context $context,\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory)
    {
        $this->resultJsonFactory = $resultJsonFactory;
        parent::__construct($context);
    }

    public function execute()
    {
       $response = $this->resultJsonFactory->create();
       $response->setData(['test' => 'hello']);
       return $response; 
    }
}

hope its work for you

Related Topic