6

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));
        }
})
2
  • Inspect through Firebug. I think URL is wrong. First check it's going to constructor or not
    – Jackson
    Sep 26, 2016 at 9:11
  • url is not wrong, When I write this code in my class, it send back the response: protected $_resultPageFactory; public function __construct(Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory) { $this->_resultPageFactory = $resultPageFactory; parent::__construct($context); } public function execute() { echo "success"; } Sep 26, 2016 at 9:13

2 Answers 2

13

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;
    }
}
9
  • It says 404 not found. But, when I do comment getPost, it gives me 500 error. Sep 26, 2016 at 9:30
  • @AbhishekDhanrajShahdeo updated the code kindly check n feedback Sep 26, 2016 at 9:36
  • you need to extends class with Action Sep 26, 2016 at 9:38
  • Error : {"readyState":4,"responseText":"","status":500,"statusText":"Internal Server Error"} Sep 26, 2016 at 9:39
  • 1
    @Qasir, it is not working Sep 26, 2016 at 10:09
8

Try with below code in controller,

<?php

namespace Vendor\Modulename\Controller\Index;

use Magento\Framework\Controller\ResultFactory;    

class Custom extends \Magento\Framework\App\Action\Action
{
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Json\Helper\Data $jsonHelper,
        \Magento\Framework\View\Result\PageFactory $resultFactory
    ) {
        $this->jsonHelper = $jsonHelper;
        $this->resultFactory = $resultFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        /** @var \Magento\Framework\View\Result\Page $resultPage */
        $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE);

        /** @var \Magento\Framework\Controller\Result\Raw $response */
        $response = $this->resultFactory->create(ResultFactory::TYPE_RAW);
        $response->setHeader('Content-type', 'text/plain');
        $data1 = 'This is test';
        $data2 = 20;
        $response->setContents(
            $this->jsonHelper->jsonEncode(
                [
                    'data1' => $data1,
                    'data2' => $data2,
                ]
            )
        );
        return $response;
    } 
}

Inside jquery,

jQuery.ajax({
      url: "/modulename/index/custom",
      type: 'POST',
      dataType: 'json',
      data: {},
      complete: function(response) {             
          stores = response.responseJSON.data1;
          selectedStore = response.responseJSON.data2;          
          console.log(data1+' '+data2);   
          },
          error: function (xhr, status, errorThrown) {
              console.log('Error happens. Try again.');
          }
    }); // ajax function end here
2
  • Recoverable Error: Argument 1 passed to MyNameSpace\ModuleName\Controller\Index\Custom::__construct() must be an instance of Magento\Framework\App\Action\Context, instance of Magento\Framework\App\Request\Http given, called in /var/www/html/magento2/var/generation/MyNameSpace/ModuleName/Controller/Index/Custom/Interceptor.php on line 14 and defined in /var/www/html/magento2/app/code/MyNameSpace/ModuleName/Controller/Index/Custom.php on line 11 Sep 26, 2016 at 9:52
  • try with updated code Sep 26, 2016 at 10:09

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.