Return bool gives error “Invalid return type” for Ajax Controller
Pregunta
I want to call this controller through Ajax and have it return true or false. the methods all work correctly, however I get the error
Invalid return type C:\Sites\retracted\wwwroot\vendor\magento\framework\App\Bootstrap.php(258): Magento\Framework\App\Http->launch()
So I assume with extends Action I can't simply return a boolean - but what should it be to allow me to return a bool?
use \Magento\Framework\App\Action\Action;
class IsEmailRegistered extends Action implements \Magento\Framework\DataObject\IdentityInterface
{
...
public function execute()
{
$result = $this->voucherHelper->validateEmail($email);
return $result;
}
}
Solución
Try this example:
protected $resultJsonFactory;
/**
* @param Context $context
* @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
*/
public function __construct(
Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
)
{
$this->resultJsonFactory = $resultJsonFactory;
parent::__construct($context);
}
/**
* Collect relations data
*
* @return \Magento\Framework\Controller\Result\Json
*/
public function execute()
{
$result = $this->voucherHelper->validateEmail($email);
/** @var \Magento\Framework\Controller\Result\Json $result */
$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData(['success' => $result]);
}
But in your code you should parse the answer as JSON.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange