2

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."}

2 Answers 2

8

Try this

Add form key in your form

<input name="form_key" type="hidden" value="<?php echo $block->getFormKey();?>">

To get the controller url.

$this->getUrl(" ");
6
  • Now i get this error [2020-09-07 08:59:57] main.DEBUG: URI '/admin/customer/index/edit/id/23/key/ee1f5626d4c89e0aaf91ffd421a7d1c736609c000b48112216c4ca2d871896c7/XX/Pricing/Controller/SaveFamilyPriceChanges?isAjax=true'' cannot be accessed with POST method (Magento\Customer\Controller\Adminhtml\Index\Edit) [] [] [2020-09-07 08:59:57] main.DEBUG: Request validation failed for action
    – gazZz
    Sep 7, 2020 at 9:01
  • And the error from "errorThrown" in javascript is "Not Found"
    – gazZz
    Sep 7, 2020 at 9:03
  • Add this in your form <input name="form_key" type="hidden" value="<?php echo $block->getFormKey();?>"> Sep 7, 2020 at 9:05
  • Check updated answer Sep 7, 2020 at 9:06
  • Could the issue be the url? looks like its adding it to the end of the current url in the error message "URI '/admin/customer/index/edit/id/23/key/ee1f5626d4c89e0aaf91ffd421a7d1c736609c000b48112216c4ca2d871896c7/XX/Pricing/Controller/SaveFamilyPriceChanges?isAjax=true''
    – gazZz
    Sep 7, 2020 at 9:08
0

Try This

<?php

$get_url = $this->getUrl("pricing/controller/savefamilypricechanges");

//use this type of name adminroutename/admincontrolername/actionfilename 

?>

<script type="text/javascript">
    require(["jquery"],function($) {
        $('#savePricing').click(function() {
            var customurl = "<?= $get_url ?>";
            $.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>

Update

<?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;

    private $formKey;
   
    /**
     * @param JsonFactory $resultJsonFactory
     */
    public function __construct(
        JsonFactory $resultJsonFactory,
        \Magento\Framework\Data\Form\FormKey $formKey,
        Session $customerSession
    ) {
        $this->resultJsonFactory = $resultJsonFactory;
        $this->formKey = $formKey;
        $this->customerSession = $customerSession;
    }

    /**
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Json|\Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {   
        $formkey = $this->formKey->getFormKey();
        $response = $this->resultFactory
             ->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON)
             ->setData([
                 'form_key' => $formkey,
                 'status'  => "ok",
                 'message' => "form submitted correctly"

             ]);

        return $response;   
    }
}

I Hope This Helps You.

2
  • I'm now getting Uncaught Error: Call to a member function dispatch() on null in /domains/xxxx/http/vendor/magento/framework/App/Action/Action.php:97
    – gazZz
    Sep 7, 2020 at 9:46
  • please share your block and phtml file code.
    – Msquare
    Sep 7, 2020 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.