Here is my Ajax Call. I call it inside click() function with jQuery.
var customurl = gpImageTagLoadUrl + '?isAjax=true';
$.ajax({
url: customurl,
method: 'POST',
data: {element_id: 11},
dataType: 'json',
success: function (data) {
console.log(data.element_id);
}
});
In the other Script i call:
window.gpImageTagLoadUrl = '<?= /** @noEscape */ $this->getUrl('pluginName/caller/loadproduct')?>';
Inside the php function I call the execute function:
public function execute()
{
$variable = $this->configs->create();
$item = $variable->addFieldToFilter('id', 11);
return $item;
}
I can call this function but i get this error:
InvalidArgumentException): Invalid return type
Any Ideas? What is the right way to create Ajax Load Function in Magento 2?
1 Answer 1
You need to encode the result to JSON before returning it from the controller.
In your constructor inject object of
Magento\Framework\Controller\Result\JsonFactory
Example:
public function __construct(
Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
) {
$this->resultJsonFactory = $resultJsonFactory;
}
Then create resultJson object
$resultJson = $this->resultJsonFactory->create();
Then create an array with key and response as your variable as follows:
$response = ['result' => $item];
Then return the encoded response from the controller as follows:
return $resultJson->setData($response);
On the jquery end, you will need to decode the JSON response
success: function(response) {
item = response.responseJSON.result;
},
error: function (xhr, status, errorThrown) {
console.log('An error occurred on the server');
}
});