So I have the following AJAX Post request within vendor/MyModule/view/frontend/templates:

let controllerUrl = "<?php echo $block->getUrl('MyModule/index/GetDates'); ?>";

$.post(controllerUrl, {
    "day": new Date().getDay(),
    "month": new Date().getMonth(),
    "year": new Date().getFullYear()
.done(function(data, status){
    console.log("Data: " + data);
    console.log("Error Retrieving from Database");day

The controller that is being pointed to is stored under vendor/MyModule/Controller/Index/GetDates.php

However, every time I run this post request I get the return status code of 401 Unauthorised. I have tried adding a form key in to the post data although this made no difference.

I have also got a very similar AJAX Post request happening within the adminhtml part of my module and that works without problems. Any suggestions welcome on resolving this issue.

Update: The GetDates.php looks like so:


namespace vendor\MyModule\Controller\Index;

class GetDates extends \Magento\Backend\App\Action

    protected $_resource;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\App\ResourceConnection $resource
    ) {  
        $this->_resource = $resource;

    //Every time the controller is called this function is executed
    public function execute(){
        $day = $this->getRequest()->getParam('day');
        $month = $this->getRequest()->getParam('month');
        $year = $this->getRequest()->getParam('year');
        echo $this->getDates($day, $month, $year);

    private function getDates($day, $month, $year){
        return true;

  • 1
    As a colleague pointed out. Magento 2 controllers require different abstract classes for authentication when switching between frontend and backend controllers. So where I was doing \Magento\Backend\App\Action I actually needed \Magento\Framework\App\Action\Action – A. Fletcher Mar 4 at 15:54

Your Answer

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

Browse other questions tagged or ask your own question.