Introduction
AJAX plays an important role in Magento 2 when you want to update data on the page without a full reload.
Its Common use cases include loading dynamic content, validating data, fetching customer-specific information, or building custom admin and frontend features.
In Magento 2, returning JSON responses from an AJAX controller is the recommended and clean approach. This blog explains how to return JSON data from an AJAX call in Magento 2 with a simple example.
For that, we can use the Magento core class,
Magento\Framework\Controller\ResultFactory
which has a list of constants 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'
Create an AJAX Controller
Magento 2 provides a dedicated JSON result type to return data in JSON format.
<?php
namespace Vendor\Module\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
class Ajax extends Action
{
protected $resultJsonFactory;
public function __construct(
Context $context,
JsonFactory $resultJsonFactory
) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
}
public function execute()
{
$result = $this->resultJsonFactory->create();
$data = [
'success' => true,
'message' => 'JSON response returned successfully'
];
return $result->setData($data);
}
}
Call AJAX from Frontend (jQuery Example)
Magento 2 includes jQuery by default, so you can easily make an AJAX request.
require(['jquery'], function ($) {
$.ajax({
url: '/module/index/ajax',
type: 'POST',
dataType: 'json',
success: function (response) {
console.log(response.message);
}
});
});
JSON Response Output
The controller returns a JSON response like this:
{
“success”: true,
“message”: “JSON response returned successfully”
}
If you require technical support, feel free to email us at [email protected].
Additionally, explore a wide array of solutions to boost your store’s capabilities by visiting the Adobe Commerce modules section.
For expert advice or to create tailored features, hire Adobe Commerce Developers for your project.
Be the first to comment.