How can I make my controller return JSON back to my template PHTML
-
06-03-2021 - |
Вопрос
Controller:
<?php
namespace MyCompany\ExampleAdminNewPage\Controller\Adminhtml\Product;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
class Product extends \Magento\Framework\App\Action\Action
{
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
}
/**
* @return \Magento\Framework\Controller\Result\Json
*/
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
}
}
Calling from PHTML:
fetch('http://localhost:8888/magento2/rest/V1/integration/admin/token', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow',
referrer: 'no-referrer',
body: JSON.stringify({
"username": "admin",
"password": "admin1@admin.com"
}),
})
.then(response => response.json())
.then(token => {
(function($) {
$.ajax({
type: "POST",
url: "<?php echo $block->getUrl('*/product'); ?>",
data: dataBody,
dataType: "json",
contentType: "application/json",
beforeSend: function(xhr) {
xhr.setRequestHeader ("Authorization", "Bearer " + token);
xhr.setRequestHeader ("Content-Type", "application/json");
if (xhr && xhr.overrideMimeType) {
xhr.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(html) {
console.log("success: ", html);
}
});
})(jQuery);
});
However, when I try to do this on I can see that the URL is correct but it returns 401 Unauthorized
Request URL: http://localhost:8888/magento2/admin/exampleadminnewpage/product/index/key/bfa7629e0c8323d434158ed68e5dd61f9e0d8ca428f859eb916412c740c89d72/
Request Method: POST
Status Code: 401 Unauthorized
And I can see this error in the Debug Logs
main.DEBUG: Request validation failed for action "Magento\Framework\App\Action\Forward\Interceptor" [] []
Any Idea what is happening here? I am new to Magento and PHP.
Решение
Turns out my Controller had the wrong class name.
The file was named Index.php but the class name there says Product...
Не связан с magento.stackexchange