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

3 Answers 3

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
0

In Magento 2.4.5-p1 we can use jQuery Ajax like below.

Write below code in js file:

define(
    [
        'jquery',
        'mage/url'
    ],
    function (
        $,
        url
    )  {
        'use strict';
        
                var orderId = 2333;
            
                getCheckoutId: function() {

                        var endpointUrl = url.build('test/ajax/response');

                        return $.post(endpointUrl, {
                            "orderId": orderId
                    }).done(function(response) {
                        console.log(response);
                    })
                }
        }
);

Write the below code in the controller file:

<?php
namespace Ajax\Demo\Controller\Ajax;

use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\Action;

class Response extends Action implements HttpPostActionInterface
{
    /**
     * @var Magento\Framework\Controller\Result\JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    /**
     * Index constructor.
     *
     * @param Magento\Framework\App\Action\Context $context
     * @param Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
     * @param \Psr\Log\LoggerInterface $logger
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        \Psr\Log\LoggerInterface $logger
    ) {
        $this->resultJsonFactory = $resultJsonFactory;
        $this->logger = $logger;
        parent::__construct($context);
    }

    /**
     *
     * @return \Magento\Framework\Controller\ResultInterface
     *
     */
    public function execute()
    {
        $resultJson = $this->resultJsonFactory->create();

        try {
            $orderId = $this->getRequest()->getParam('orderId', '');
            $checkoutId = 123456;

            $resultJson->setData([
                'checkoutId' => $checkoutId,
                'success' => true
            ]);
            
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());
        }

        return $resultJson; 
    }
}

Your Answer

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

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