Magento 2 - Ajax is not calling Controller

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

We need to add use Magento\Framework\App\Action\Context at the first of class. Or, change Context to Magento\Framework\App\Action\Context. Remove the comma \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,.

Your controller should extend from \Magento\Framework\App\Action\Action

Add the json variable $resultJsonFactory.

namespace MyCompany\MyModule\Controller\Index;

use Magento\Framework\App\Action\Context;

class GetAjax extends \Magento\Framework\App\Action\Action {

    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.


The problem with

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

replace with

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

Complete code

 <?php

namespace MyCompany\MyModule\Controller\Index

use Magento\Framework\App\Action\Action;
use Magento\Framework\Controller\ResultFactory;

class GetAjax extends Action {

    protected $resultJsonFactory;

    public function __construct(
           Context  $context

    ) {

        parent::__construct($context);
    }


    public function execute() {
    /* @var \Magento\Framework\Controller\Result\Json $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


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