Recently working on a custom extension development, we came across the requirement of using third-party API integration along with AJAX to save time and efforts of consumers. Keeping client’s requirement in mind and going through docs of API, we finally decided to use JSON response to reduce response time and data transmitted between extension and API server. To increase the efficiency of extension we have added a topping of AJAX to display data on the same page. Presenting guide to returning JSON data from controller While calling ajax in Magento 2.
By default, Magento has served a list of TYPE_JSON constant variables in ResultFactory. Magento\Framework\Controller\ResultFactory
Among which, here we have used json to fulfill the purpose but you can use any constant variable as per your requirement.
1. const TYPE_JSON = ‘json’
2. const TYPE_RAW = ‘raw’
3. const TYPE_REDIRECT = ‘redirect’
4. const TYPE_FORWARD = ‘forward’
5. const TYPE_LAYOUT = ‘layout’
6. const TYPE_PAGE = ‘page’
Firstly, create ‘Jsonrequest.php’ file in at below path using following code.
Because $this->resultFactory object is already defined in Magento\Framework\App\Action\Context we don’t need to create another.
class Jsonrequest extends \Magento\Framework\App\Action\Action
public function __construct(
public function execute()
/* Create array for return value */
$response['value1'] = "Value one";
$response['value2'] = "Value Two";
$response['value3'] = "Value Three";
$resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON); //create Json type return object
$resultJson->setData($response); // array value set in Json Result Data set
return $resultJson; // return json object
Congratulations! You are done. You have successfully returned json data from controller. You can use or modify this code according to your convenience and requirement.
Lastly, comment down below if you are looking for any help regarding this code and tell us how you have used this code. Stay tuned for more.