Magento2 – Retrieve and Return Response from Controller

ajaxcontrollersmagento2response

I have a problem in which I'm making an AJAX call to a controller. But, I am not able to check whether it is working or not. I also want to return data in response. But, it keeps throwing some errors. Below is my code:

<?php
namespace MyNameSpace\MyModule\Controller\Index;

class Custom {
    protected $request;
    public function __construct(\Magento\Framework\App\Request\Http $request) {
        $this->request = $request;
    }

    public function getPost() {
        return $this->request->getPost();
    }

    public function __execute() {
        echo "success";
    }
}

But I keep receiving some or the other errors, below is my AJAX call and it is working and sending proper data:

$.ajax({
        url : url,
        type : 'post',
        data : data,
        success : function(result) {
            console.log(result);
        },
        error : function(err) {
            console.log("Error : "+JSON.stringify(err));
        }
})

Best Answer

ajax

<script>
require(['jquery', 'jquery/ui'], function($){ 


      $.ajax({
          method: "POST",
          url: "<?php  echo $block->getUrl('modulanefrontname/ajax/search'); ?>",
          data: { q: 'some' },
          dataType: "json"
        })
      .done(function( msg ) {

       /do your thing

      });


 });

you can use ResultFactory controller

<?php
namespace MyNameSpace\MyModule\Controller\Index;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;



class Custom extends Action {
    protected $request;
    public function __construct(Context $context,array $data = []) {
        parent::__construct($context,$data);
    }



    public function __execute() {
       if ($this->getRequest()->getPost('q')):
        $query=$this->getRequest()->getPost('q');
                  $data=array("bdfb");
        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData($data);
        return $resultJson;
    endif;
    }
}