Menu Close
    Hire Us Request Quote Reading List Switch to Dark Mode

    Return JSON Data with AJAX call in Magento 2

    Today, we will see how to return json data from controller while doing an ajax call.
    Situation may come that you are doing some customization and need to deal will json data from controller then here is the way how we can go for it.

    For that we can use the magento core class,

    Magento\Framework\Controller\ResultFactory

    which has list of constant mapped to corresponding classes :

    self::TYPE_JSON => 'Magento\Framework\Controller\Result\Json',
    self::TYPE_RAW => 'Magento\Framework\Controller\Result\Raw',
    self::TYPE_REDIRECT => 'Magento\Framework\Controller\Result\Redirect',
    self::TYPE_FORWARD => 'Magento\Framework\Controller\Result\Forward',
    self::TYPE_LAYOUT => 'Magento\Framework\View\Result\Layout',
    self::TYPE_PAGE => 'Magento\Framework\View\Result\Page'

    among these, we can use the constant to return json data :

    const TYPE_JSON = 'json';

    Now here is the complete code to implement above.

    <?php
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @package   Webkul_<modulename>
     * @author    Webkul Software Private Limited
     * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     */
    namespace Webkul\<modulename>\Controller\Attachment;
    
    use Magento\Framework\Controller\ResultFactory;
    
    class <action> extends \Magento\Framework\App\Action\Action
    {
    
        /**
         * @var \Magento\Framework\App\Action\Contex
         */
        private $context;
    
        /**
         * @param \Magento\Framework\App\Action\Context $context
         */
        public function __construct(
            \Magento\Framework\App\Action\Context $context
        ) {
            parent::__construct($context);
            $this->context           = $context;
        }
    	
        /**
         * @return json
         */
        public function execute()
        {
            $whoteData = $this->context->getRequest()->getParams();
            $resultJson->setData(["message" => ("Invalid Data"), "suceess" => true]);
            return $resultJson;
        }
    }
    

    This is all we need , hope this help you out. happy coding.

    . . .

    Comment

    Add Your Comment

    Be the first to comment.

    Back to Top
    css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close