0

I made an ajax script to (at the moment) simply return some HTML to a select.

My function looks like this:

$.ajax({
    showLoader: true,
    data: {val: inputVal},
    /*dataType: 'json', (un)commenting this doesn't change anything*/
    url: '/garage/data/get',
    type: 'post',
    success: function(res) {console.log(res)},
    error: function(res) {console.log(res)}
})

My Data/Get.php controller file:

<?php
    namespace Vendor\Module\Controller\Data;

    use Magento\Framework\App\Action\Context;

    class Get extends \Magento\Framework\App\Action\Action
    {
       protected $resultJsonFactory;

        public function __construct(
            Context $context,
            \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
        )
        {
            $this->resultJsonFactory = $resultJsonFactory;
            parent::__construct($context);
        }

        public function execute()
        {
            $result = $this->resultJsonFactory->create();

            if ($this->getRequest()->isAjax()) {
               return '<option>treyBake was here</option>';
            }
        }
    }

Triggering the AJAX call returns this in console:

Error log record number: 1086239430194

Going to that log shows:

{"0":"Invalid return type","1":"#0 /var/www/magento2-site/vendor/magento/framework/App/Bootstrap.php(256): Magento\Framework\App\Http->launch()\n#1 /var/www/unity/pub/index.php(41): Magento\Framework\App\Bootstrap->run(Object(Magento\Framework\App\Http\Interceptor))\n#2 {main}","url":"/garage/data/get","script_name":"/index.php"}

The main error from that mess:

Invalid return type

How do I go about debugging/resolving this error?

Edit: code I've tried:

Data/Get.php

<?php
    namespace Vendor\Module\Controller\Data;

    class Get extends \Magento\Framework\App\Action\Action
    {
        protected $resultJsonFactory;
        protected $resultFactory;

        public function __construct(
            \Magento\Framework\App\Action\Context $context,
            \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
            \Magento\Framework\Controller\ResultFactory $resultFactory
        )
        {
            $this->resultJsonFactory = $resultJsonFactory;
            $this->resultFactory = $resultFactory;

            parent::__construct($context);
        }

        public function execute()
        {
            $result = $this->resultJsonFactory->create();
            $response = '200';

            $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
            $resultJson->setData($response);

            return $resultJson;
        }
    }

With my js in my .phtml template file as:

<script type="text/javascript">
    require(['jquery', 'module'], function($, script)
    {
        //<![CDATA[
        jQuery(document).ready(function($)
        {
            $('select.filter-select').change(function()
            {
                let ajaxReq,
                    value = $(this).val();

                ajaxReq = $.ajax({
                    url: '<?php echo $block->getUrl("module/data/get"); ?>',
                    type: 'post',
                    showLoader: true,
                    data: {val: value}
                });

                ajaxReq.done(function(res, txtStatus, jqXHR)
                {
                    console.log(res);
                });

                ajaxReq.fail(function(XMLHttpRequest, txtStatus, err)
                {
                    console.log(XMLHttpRequest);
                    console.log(txtStatus);
                    console.log(err);
                });
            });
        });
        //]]>
    });
</script>

This returns:

There has been an error processing your request

Exception printing is disabled by default for security reasons.

Error log record number: 616547725800

Going to var/report/616547725800 shows:

{"0":"Source class \"\Vendor\Module\Controller\Data\Result\" for \"Vendor\Module\Controller\Data\ResultFactory\" generation does not exist."

This happens both before and after the below commands:

$ php bin/magento setup:upgrade
$ php bin/magento setup:di:compile
$ php bin/magento setup:static-content:deploy -f
$ php bin/magento cache:flush
0

If you really just want to send data from PHP controller to javascript, you can archive it by changing JsonFactory to RawFactory. Of course, you have to return instance of object which factory creates with filled data. Your code should look like this :

use Magento\Framework\App\Action\Context;

class Get extends \Magento\Framework\App\Action\Action
{
   protected $resultRawFactory;

    public function __construct(
        Context $context,
        \Magento\Framework\Controller\Result\RawFactory $resultRawFactory
    ) {
        $this->resultRawFactory = $resultRawFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $result = $this->resultRawFactory->create();

        if ($this->getRequest()->isAjax()) {
           return $result->setContents('<option>treyBake was here</option>');
        }
    }
}

... however this is not good practice ( not Magento nor Web ). For better solution I would return JsonFactory instance with set data ( array ), but you have to parse them on javascript side also. The best solution would be to use webapi as @philip-sander suggested. ( but this topic is far more bigger )

0
<script type="text/javascript">
    //<![CDATA[
    jQuery("#login-form").submit(function(event) { // On submit form.
        var ajaxRequest;
        event.preventDefault();
        var values = jQuery(this).serialize(); //serialize form data.
        var url=jQuery(this).attr("action");

            ajaxRequest = jQuery.ajax({
                url: "<?php echo $block->getUrl('frontname/controllerfolder/controllername'); ?>",
                type: "POST",
                beforeSend: function () {
                    jQuery('#loader').show();
                },
                data: values
            });

            ajaxRequest.done(function (response, textStatus, jqXHR) {
                // show successfully for submit message
                jQuery("#ajaxResponse").html(response);
                jQuery('#loader').hide();
                if(response == '200'){
                    jQuery("#ajaxResponse").html('Good !');
                }
            });

            /* On failure of request this function will be called  */
            ajaxRequest.fail(function (XMLHttpRequest, textStatus, errorThrown) {

                console.log('error textStatus', textStatus);
                console.log('error errorThrown', errorThrown);

                // show error
                jQuery("#ajaxResponse").html('Oups, Error');
                jQuery('#loader').hide();
            });
    });
    //]]>
</script>

Controller :

<?php
    namespace Vendor\Module\Controller\Data;

    use Magento\Framework\App\Action\Context;

    class Get extends \Magento\Framework\App\Action\Action
    {
       protected $resultJsonFactory;
       protected $resultFactory;    

        public function __construct(
            \Magento\Framework\App\Action\Context $context, //updated
            \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
            \Magento\Framework\Controller\ResultFactory
        )
        {
            $this->resultJsonFactory = $resultJsonFactory;
            $this->resultFactory = $resultFactory;
            parent::__construct($context);
        }

        public function execute()
        {
            $result = $this->resultJsonFactory->create();
            $response ='200';
            $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
            $resultJson->setData($response);
            return $resultJson;
        }
    }
  • Ok so after all changes I get internal server error in the console - I did add ini_set to the top of the class to see if it would return any errors but nada - any way to debug? – treyBake Dec 19 '18 at 10:50
  • Ok managed to get the error returned: Source class \"\\Vendor\\Module\\Controller\\Data\\Result\" for \"Vendor\\Module\\Controller\\Data\\ResultFactory\" generation does not exist – treyBake Dec 19 '18 at 11:46
  • try : php bin/magento setup:di:compile – PЯINCƏ Dec 19 '18 at 12:12
  • Already tried^^ – treyBake Dec 19 '18 at 12:12
  • Remove the content var/generation or generated then compile again. – PЯINCƏ Dec 19 '18 at 12:19

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.