7

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 MyCompany\MyModule\Controller\Index;

class GetAjax extends \Magento\Backend\App\AbstractAction {

        public function __construct(
               Context  $context,
               \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        ) {

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


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

1
  • 1
    I updated my answer: Your controller should extend from \Magento\Framework\App\Action\Action. Commented Dec 15, 2016 at 13:40

3 Answers 3

7

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.

8
  • Although it did not solve the error. Thank you, I completly forgot that. I only used $(document).ready for testing.
    – TrytoFly
    Commented Dec 15, 2016 at 12:57
  • Still not working? Try to remove var/generation? Commented Dec 15, 2016 at 12:58
  • Sadly no, i still get a Error 500.
    – TrytoFly
    Commented Dec 15, 2016 at 13:03
  • Is there any error log? You check the network and see your Ajax request? Commented Dec 15, 2016 at 13:11
  • Ah! I saw that you forgot to add the json variable protected $resultJsonFactory; Commented Dec 15, 2016 at 13:15
3

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

2
  • This sadly did not solve the problem.
    – TrytoFly
    Commented Dec 15, 2016 at 14:16
  • @TrytoFly added the complete code that i am using also the example in magento too Commented Dec 16, 2016 at 5:40
2

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

1
  • I tried that, does not make a change. I still recieve the same error´s.
    – TrytoFly
    Commented Dec 15, 2016 at 13:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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