Magento 2 – Ajax is not calling Controller

The question:

I tried to make a simple ajax-call to my controller.

Somehow I don’t get a valid response.

MyCompany/MyModule/Index/GetAjax.php

namespace MyCompanyMyModuleControllerIndex;

class GetAjax extends MagentoBackendAppAbstractAction {

        public function __construct(
               Context  $context,
               MagentoFrameworkControllerResultJsonFactory $resultJsonFactory,
        ) {

            $this->resultJsonFactory = $resultJsonFactory;
            parent::__construct($context);
        }


        public function execute() {
        /** @var MagentoFrameworkControllerResultJson $result */
        $result = $this->resultJsonFactory->create();
        return $result->setData(['success' => true]);
       } 
}

MyCompany/MyModule/etc/frontend/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="mymodule" frontName="mymodule">
            <module name="MyCompany_MyModule" />
        </route>
    </router>
</config>

MyCompany/MyModule/view/frontend/web/js/test.js

define(['jquery'],
    function ($) {
         $(document).ready(function() {

              $.ajax({

                url : 'mymodule/index/getAjax',
                type : 'GET',
                data: {
                    format: 'json'
                },
                dataType:'json',
                success : function(data) {              
                    alert('Data: '+data);
                },
                error : function(request,error)
                {
                    alert("Error");
                }
            });

         });
    });

I get my error message and in my console I get

JQMIGRATE: jQuery.parseJSON requires a valid JSON string.

Besides if I try to enter mymodule/index/getAjax url in my browser there is a

Error 500 (internal server error)

Can anyone help me out?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Error 500 (internal server error) – something went wrong on the server side.

We need to add use MagentoFrameworkAppActionContext at the first of class. Or, change Context to MagentoFrameworkAppActionContext. Remove the comma MagentoFrameworkControllerResultJsonFactory $resultJsonFactory,.

Your controller should extend from MagentoFrameworkAppActionAction

Add the json variable $resultJsonFactory.

namespace MyCompanyMyModuleControllerIndex;

use MagentoFrameworkAppActionContext;

class GetAjax extends MagentoFrameworkAppActionAction {

    protected $resultJsonFactory;
    ......

}

In your Ajax function, need to remove (or add json format data with JSON.stringify)

data: {
      format: 'json'
  },

Remove var/generation and try to make the Ajax again.

There is a note that it’s not good: making the Ajax request when the document DOM ready.

Method 2

The problem with

$result = $this->resultJsonFactory->create();

replace with

$result = $this->resultJsonFactory->create(ResultFactory::TYPE_JSON);

Complete code

 <?php

namespace MyCompanyMyModuleControllerIndex

use MagentoFrameworkAppActionAction;
use MagentoFrameworkControllerResultFactory;

class GetAjax extends Action {

    protected $resultJsonFactory;

    public function __construct(
           Context  $context

    ) {

        parent::__construct($context);
    }


    public function execute() {
    /* @var MagentoFrameworkControllerResultJson $result */

        $resultJson = $this->resultJsonFactory->create(ResultFactory::TYPE_JSON);
        return $resultJson->setData(['success' => true]);
   } 
}

for reference you can see vandor/magento/module-search/Controller/Ajax/Suggest.php

Method 3

Error is due to url

define(['jquery'],
    function ($) {
         $(document).ready(function() {

              $.ajax({

                url : 'http://www.yourdomain.com/mymodule/index/getAjax',
                type : 'GET',
                data: {
                    format: 'json'
                },
                dataType:'json',
                success : function(data) {              
                    alert('Data: '+data);
                },
                error : function(request,error)
                {
                    alert("Error");
                }
            });

         });
    });

Use above code url should be http://www.yourdomain.com/mymodule/index/getAjax instead of mymodule/index/getAjax


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment